/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/03 11:05:40
 */

var dependsList = [
    'index', 'layer', 'form', 'table', 'laydate',
    'util', 'zmn_validate', 'zmnUtils', '$http', 'select2',
    'validator', 'Vue', 'dayjs', 'zmnOmsSelect', 'clipboard'
];

layui.define(dependsList, function(exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var validate = layui.zmn_validate;
    var util = layui.util;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var Vue = layui.Vue;
    var dayjs = layui.dayjs;
    var table = layui.table;
    let zmnOmsSelect = layui.zmnOmsSelect;
    var clipboard = layui.clipboard;

    var debounceTimer;
    var orderPostTable;
    var maxProductCount = 1;
    var countyData = [];
    var isGrid;
    var gridCompanyId;
    var orderGridCompanyId = json.orderGridCompanyId;
    var branchCompany = json.branchCompany;
    var isAvailableWeek;
    var changeDutyData; // 改约对象

    window.EventBus = new Vue();

    var objOfURL = {
        workDetail: '/work/detail.action',
        workModifyDetail: '/work/modify/detail.action',
        savePurpose: '/order/purpose/save.action'
    };

    var options = {
        saveURL: null,
        isNew: false,
        isEntrust: false,
        modifyDetail: false,
        enableExternalShop: false,
        success: () => {},
        verifyUrl: null,
    };

    // 检查价格表工单产品数量是否为1
    var isQuotationCanSave = () => {
        var flag = true;

        var servItemType = getters.getServItemType();
        var count = getters.getCount();
        if (isQuotation(servItemType) && !(count == 1)) {
            flag = false;
            layer.msg('计价器工单产品数量必须为1')
        }

        return flag;
    }

    function verifyBeforeSubmit() {
        // 计价器产品数量必须为1
        if (!isQuotationCanSave()) {
            return false;
        }
        return true;
    }

    function verifyChangeAddressOrDutyTimeOrProduct(callback, params) {

        if (!options.isUpdate) {
            callback(params);
            return;
        }

        $http.save(options.verifyUrl, params).then(function(data) {
            if (data != null) {
                if (data.indexOf("工程师城市不符合") != -1 || data.indexOf("工程师服务公司不符合") != -1 ||
                    data.indexOf("工程师技能不匹配") != -1 || data.indexOf("工程师不在服务范围") != -1 ||
                    data.indexOf("行政子公司发生变更") != -1) {
                    layer.open({
                        title: '修改工单',
                        btn: ['确认', '取消'],
                        content: data,
                        yes: function(index, layero) {
                            layer.close(index);
                            callback(params);
                        },
                        btn2: function(index, layero) {
                            layer.close(index);
                        }
                    });
                } else {
                    layer.open({
                        title: '修改工单',
                        btn: ['确认并撤回', '确认但不撤回'],
                        content: data,
                        yes: function(index, layero) {
                            layer.close(index);
                            callback(params);
                        },
                        btn2: function(index, layero) {
                            layer.close(index);
                            params.isVerifyDistributeBack = false;
                            callback(params);
                        }
                    });
                }
            } else {
                callback(params);
            }
        }, function(msg) {
            layer.msg(msg);
        })
    }

    // 城市
    var cityData = {};

    var NORMAL_ORDER_ADD_URL = '/order/normal/add.action';

    // 获取省份、城市、区域
    var CITY_URL = '/area/permit/city/list.action';
    var COUNTY_URL = '/area/list.action';
    var AREA_DETAIL_URL = '/area/detail/list.action';
    var CHECK_CHANNELID_CITYID_URL = '/area/check/channel_city.action';

    // 获取公司信息
    var COMPANY_URL = '/company/getCompanyName.action';
    // 获取行政服务商名称
    var GRID_COMPANY_URL = "/company/getGridCompanyName.action";

    // 渠道订单配置
    var GET_CHANNEL_CONF_URL = "/conf/channel/getChannelInfo.action";
    // 外部店铺数据
    var GET_EXTERNAL_SHOP_URL = "/shop/list/marketing.action";

    // 获取产品列表
    var PRODUCT_URL = '/serv/product/list.action';

    // 获取常见故障
    var PRODUCT_SUBSIDIARY_URL = '/serv/product/subsidiary/list.action';

    // 获取小区地址信息
    var COMMUNITY_ADDRESS_URL = '/area/queryCommunity.action';
    // 百度地图地址联想
    var BAIDU_MAP_SUGGESTED = "//api.map.baidu.com/place/v2/suggestion";

    // 校验地址是否在服务范围
    var STREET_VALIDATION_URL = '/area/checkServicePoint.action';

    // 根据经纬度获取区域信息
    var AREA_INFO_URL = '/area/getAreaInfo.action';

    // 检查返修单源单号
    var CHECK_REWORD_ID_URL = '/order/check/rework.action';

    // 产品价格表页面地址
    var PRODUCT_PRICE_TABLE_URL = '/order/getProductPriceTable';

    // 提前报价价格表页面地址
    var ADVANCE_PRODUCT_PRICE_TABLE_URL = "/order/advance/getProductPriceTable";

    // 提前报价故障现象价格表页面地址
    var ADVANCE_PRODUCT_PHEN_PRICE_TABLE_URL = "/order/advance/getPhenProductPriceTable";

    // 判断工单是否可以改返修
    var CAN_CHANGE_REWORK = '/order/canChangeToRework.action';
    // 获取工单类型以及默认服务项信息
    var GET_SERVITEM_TYPE_INFO_WORK_URL = '/order/getServItemTypeAndInfo.action';
    // 根据渠道、城市、产品类型获取服务分类
    var GET_SERV_CATEG_BY_CITY_CHANNEL_SHOWTYPE_URL = '/serv/category/listByCityIdAndChannelIdAndShowType.action';
    // 获取默认预约时间
    var GET_DEFAULT_DUTYTIME = '/schedule/back/defaultTime.action';
    // 检查是否平台直派
    var IS_GRID = '/common/check/grid.action';
    // 获取自动派单时间
    var GET_AUTO_DISTRIBUTE_TIME = "/common/getAutoDistributeTime.action";
    var GET_DECRYPT_PHONE_URL = "/order/normal/getDecryptPhone";
    // 获取优惠页面信息
    var GET_SHOW_DISCOUNT_URL = "/work/addOrder/getDiscountURL";
    // 获取下单优惠信息
    var GET_ADD_ORDER_DISCOUNT_URL = "/work/addOrder/getDiscountDetail";
    // 校验取消重复
    let GET_DUPLICATE_ORDER_ID_URL = "/order/check/duplicateOrder";
    // 校验疫情
    let CHECK_EPIDEMIC_CONTROL = "/order/check/epidemicControl";


    // 校验提前付试点
    let CHECK_ADVANCE_QUOTE_URL = "/order/advance/checkAdvance";
    // 获取提前付相关信息
    let GET_QUOTE_INFO_URL = "/order/advance/getQuoteInfo";

    // 获取故障现象列表
    let LIST_PHEN_URL = "/order/advance/listFaultPhen";
    // 获取提前付服务项报价二级分类(故障现象)
    let LIST_PRODUCT_CATEG_WITH_PHEN_ID_URL = "/order/advance/listProductCateg";
    // 获取提前付故障现象获取产品
    let LIST_PRODUCT_WITH_PHEN_URL = "/order/advance/listProduct";

    // 获取服务项列表
    let LIST_SERVICE_ITEM_URL = "/order/advance/listServiceItem";
    // 获取提前付服务项报价二级分类
    let LIST_PRODUCT_CATEG_WITH_ITEM_ID_URL = "/order/advance/listProductCategWithItemId";
    // 获取提前付服务项获取产品
    let LIST_PRODUCT_WITH_ITEM_URL = "/order/advance/listProductWithItem";

    // 转单失败发送挽回短信
    var GET_ORDER_TRANSFER_FAIL_URL = "/sendMessage/orderTransferFail.action";
    // 话务确认报价失败
    var GET_ORDER_CONFIRM_QUOTED_FAIL_URL = "/sendMessage/orderConfirmQuotedFail.action";

    // 优惠批次信息 三层嵌套 手机号、页面产品index、批次
    // {"tel":{index:{batchId1:discountInfo,batchId2:discountInfo}}}
    // 对象
    let discountTelephoneMap = new Map();
    let bestDiscountTelephoneMap = new Map();

    // 工单类型枚举
    var ORDER_TYPE_ENUM = {
        'NEW': '1',
        'REWORK': '2'
    };

    // 产品显示类型
    var PRODUCT_SHOW_TYPE_ENUM = {
        'BACK': '1',
        'FRONT': '2'
    };

    // 服务项类型(是否是计价器工单)
    var SERVICE_ITEM_TYPE_ENUM = {
        'SERVICE_ITEM_TYPE_ORDER': '1',
        'SERVICE_ITEM_TYPE_FAULT': '2',
        'SERVICE_ITEM_TYPE_ADVANCE_PAY': '3',
        'SERVICE_ITEM_TYPE_QUOTATION_THREE': '4',
    }

    // 产品列表缓存
    var productCache = {}
    var showProductCache = {}
    var servCategoryCache = {}
    var showCheckCityMsg = false;

    function isQuotation(servItemType) {
        return SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_FAULT == servItemType ||
            SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_ADVANCE_PAY == servItemType ||
            SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_QUOTATION_THREE == servItemType;
    }

    /**
     * 远程获取产品数据
     * @param plat 平台
     * @param servCategId 服务项目 id
     * @param cb 回调函数
     */
    function fetchProductData(plat, servCategId, showType, cityId, channelId, bizType, cb) {
        var orderType = getters.getType();
        var includeDisabled = (orderType == OMS_ORDER_TYPE.ORDER_TYPE_REWORK);

        return $http.get(PRODUCT_URL, {
            plat: plat,
            servCategId: servCategId,
            showType: showType,
            cityId: cityId,
            channelId: channelId,
            bizType: bizType,
            includeDisabled: includeDisabled
        })
    }

    /**
     * 根据产品id
     * @param {string | number} productId 产品id
     * @param {function} cb 回调函数
     */
    function fetchProductSubsidiary(productId) {
        return $http.$get(PRODUCT_SUBSIDIARY_URL, { productId: productId });
    }

    /**
     * 根据父级 id 远程获取下级区域数据
     * @param {string} url 地址
     * @param {object} params 参数
     */
    function fetchAreaDataByParentId(url, params) {
        return $http.get(url, params).then(function(data) {
            return data;
        }, function() {
            layer.msg('获取数据失败');
            return $.Deferred().resolve([]);
        });
    }

    /**
     * 根据省份 id 远程获取城市数据
     * @param provinceId 城市 id
     */
    function fetchCityData(provinceId) {
        return fetchAreaDataByParentId(CITY_URL, {
            provinceId: provinceId,
            channelId: getters.getChannelId(),
            showType: getters.getProductShowType(),
        });
    }


    /**
     * 根据城市 id 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaData(cityId) {
        return fetchAreaDataByParentId(COUNTY_URL, { parentId: cityId });
    }

    /**
     * 根据城市 id 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaDetailData(pId) {
        return fetchAreaDataByParentId(AREA_DETAIL_URL, { parentId: pId });
    }

    /**
     * 根据经纬度 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaInfo(lon, lat) {
        return fetchAreaDataByParentId(AREA_INFO_URL, { longitude: lon, latitude: lat });
    }

    /**
     * 获取区县信息查询
     */
    function getCountyInfo(countyName) {
        if (!countyName) {
            return null;
        }

        if (countyData.length == 0) {
            $('#county-list').find('span').each(function() {
                var county = {
                    countyId: $(this).data('id'),
                    countyName: $(this).text(),
                };
                countyData.push(county);
            });
        }

        for (var i = 0; i < countyData.length; i++) {
            if (countyName == countyData[i].countyName) {
                return countyData[i];
            }
        }
        return null;
    }

    /**
     * 区县信息查询
     */
    function setCountyInfo(countyName, lng, lat, callback) {
        var cityId = $('#cityId option:selected').val();
        // 本地数据获取countyinfo
        countyName = countyName || '';
        let countyInfo = getCountyInfo(countyName);
        if (countyInfo) {
            updateAreaInfo(countyInfo.countyId);
            if (callback) {
                callback(countyInfo.countyId);
            }
            return;
        }

        // 调用远程接口获取countyinfo
        fetchAreaInfo(lng, lat).then(function(data) {
            if (cityId != data.cityId) {
                switchCity(data.cityId);
            }

            updateAreaInfo(data.countyId);
            if (callback) {
                callback(data.countyId);
            }
        }, function(msg) {
            layer.msg(msg);
        });
    }

    /**
     * 获取小区库的地址
     * @param params 查询参数
     * @param cb 回调函数
     */
    function fetchSuggestedStreet(params, cb) {
        fetchBaiduSuggestedStreet(params, cb);
        // $.ajax({
        //     type: "get",
        //     url: COMMUNITY_ADDRESS_URL,
        //     data: params,
        //     success: function (resultData) {
        //         if (resultData.statusBool) {
        //             if (resultData.data === undefined) {
        //                 resultData.data = [];
        //             }
        //             var data = resultData.data;
        //             // 过滤搜索结果
        //             data = data.filter((item) => {
        //                 if(!item.location){
        //                     return false;
        //                 }
        //                 return !item.city || item.city.indexOf(params.cityName.slice(0, 1)) !== -1;
        //             });
        //             cb(data);
        //         }else {
        //             console.log(params, resultData.message);
        //             // 异常，调用百度地址
        //             fetchBaiduSuggestedStreet(params, cb);
        //         }
        //     },
        //     error: function () {
        //         // 异常，调用百度地址
        //         fetchBaiduSuggestedStreet(params, cb);
        //     },
        // });
    }

    /**
     * 获取百度联想出的地址
     * @param params 查询参数
     * @param cb 回调函数
     */
    function fetchBaiduSuggestedStreet(params, cb) {
        $.ajax({
            url: BAIDU_MAP_SUGGESTED,
            type: "GET",
            dataType: "jsonp",
            data: {
                query: params.queryStr,
                region: params.cityName,
                city_limit: true,
                output: "json",
                ak: params.ak,
            },
            success: function(response) {
                if (response.status === 0) {
                    // 过滤搜索结果
                    var data = response.result.filter((item) => {
                        if (item.name == item.province || item.name == item.city || item.name == item.district || item.name.endsWith('-道路') || item.name.endsWith('镇') || item.name.endsWith('乡')) {
                            return false;
                        }
                        return (item.city.indexOf(params.cityName.slice(0, 1)) !== -1) || (!item.city && item.district.indexOf(params.cityName.slice(0, 1)) !== -1);
                    });
                    cb(data);
                }
            },
        });
    }

    /**
     * 获取公司信息
     */
    function fetchCompanyName(plat, channelId, cityId, type, dutyTime, workId, bizType, servCategId, productShowType, productId, longitude, latitude, streetSource) {
        servCategId = servCategId || 0
        productShowType = productShowType || 0
        productId = productId || 0

        var reqData = {
            plat: plat,
            channelId: channelId,
            cityId: cityId,
            countyId: getters.getCountyId(),
            streetId: getters.getStreetId(),
            type: type,
            dutyTime: dutyTime,
            workId: workId,
            bizType: bizType,
            servCategId: servCategId,
            productShowType: productShowType,
            productId: productId,
            longitude: longitude,
            latitude: latitude,
            streetSource: streetSource,
            telephone: getters.getTelephone(),
            telephone2: getters.getTelephone2(),
            telephone3: getters.getTelephone3(),
            receiveEntranceId: getters.getReceiveEntranceId(),
            requestId: getters.getRequestId()
        }

        return $http.$post(COMPANY_URL, reqData);
    }

    /**
     * 格式化公司列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatChannel(repo) {
        if (repo.loading) {
            return '查询中...'
        }
        var name = repo.text;
        var markup = '<div><div><i class="zmn-icon zmn-icon-user"></i><span>' + name + '</span></div></div>';

        return markup;
    }

    /**
     * 保存新普通订单
     * @param {object} params 订单信息
     * @param {function} cb 回调函数
     */
    function saveOrderInfo(params, btn) {
        // 移除禁用标示
        $('select,input').attr("disabled", false);

        return $http.lockSave(options.saveURL, params, btn);
    }

    /**
     * 保存心愿单
     * @param {object} params 订单信息
     * @param {btn} 按钮
     */
    function savePurpose(params, btn) {
        return $http.lockSave(objOfURL.savePurpose, params, btn);
    }

    function getLayuiSelectValue(selector) {
        return $(selector + ' option:selected').val();
    }

    function getLayuiSelectText(selector) {
        return $(selector + ' option:selected').text();
    }
    /**
     * 全局获取器
     * @type {{getCityId: (function(): jQuery)}}
     */
    var getters = {
        getInputValueById: function(id) {
            return $.trim($('#' + id).val());
        },
        getTelephoneById: function(id) {
            let $telephone = $("#" + id);
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getTelephone: function() {
            let $telephone = $("#telephone");
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getTelephone2: function() {
            let $telephone = $("#telephone2");
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getTelephone3: function() {
            let $telephone = $("#telephone3");
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getLocation: function() {
            return {
                lng: $('#longitude').val(),
                lat: $('#latitude').val()
            };
        },
        getLongitude: function() {
            return $('#longitude').val();
        },
        getLatitude: function() {
            return $('#latitude').val();
        },
        getPlat: function() {
            return $('#plat').val() || plat;
        },
        getPlatWork: function() {
            return $('#platWork').val() || $('#plat').val() || platMark.ZMN;
        },
        getType: function() {
            return $('#type').val()
        },
        getProvinceId: function() {
            return getLayuiSelectValue('#provinceId');
        },
        getCityId: function() {
            return getLayuiSelectValue('#cityId');
        },
        getCountyId: function() {
            return this.getInputValueById('countyId');
        },
        getInputCountyName: function() {
            let countyId = this.getCountyId();
            if (!countyId) return "";
            return $('#county-list').find('span[data-id=' + countyId + ']').text();
        },
        getStreetId: function() {
            return this.getInputValueById('streetId');
        },
        getCityName: function() {
            return $('#cityId option:selected').text();
        },
        getStreet: function() {
            return $('#customerAddress').val();
        },
        getStreetSource: function() {
            return $('#streetSource').val() || 0;
        },
        getAddress: function() {
            return $('input[name="address"]').val();
        },
        getServCategId: function() {
            return getLayuiSelectValue('#servCategoryId');
        },
        getProductShowType: function() {
            return $('input[name="productShowType"]:checked').val() || 2;
        },
        getProductId: function() {
            if (getters.getProductShowType() == '1') {
                return getLayuiSelectValue('#product');
            } else {
                return getLayuiSelectValue('#showProduct');
            }
        },
        getChannelId: function() {
            if ($('#type').val() == '2') {
                // 返修
                return $('#sourceChannelId').val()
            } else {
                // 新单
                return getLayuiSelectValue('#channelId');
            }
        },
        getBizType: function() {
            return $('#bizType').val() || BIZ_TYPE.C;
        },
        getDutyTime: function() {
            return $('#duty-time-input').val();
        },
        getWorkId: function() {
            return $('#work-id').val();
        },
        getOrderId: function() {
            return $('#order-id').val();
        },
        getCount: function() {
            var count = $('#count').val();
            return Number.parseInt(count) || 0;
        },
        getOrderType: function() {
            return this.getInputValueById('type');
        },
        getReworkId: function() {
            return this.getInputValueById('reworkId');
        },
        getEquityType: function() {
            return $('input[name="equityType"]:checked').val();
        },
        getServItemType: function() {
            return this.getInputValueById('servItemType');
        },
        getBrandId: function() {
            if (getters.getReceiveEntranceId() == '1002') {
                return getLayuiSelectValue('#brand');
            }
            return getLayuiSelectValue('#brand') || 1051;
        },
        getBrandIdWithoutDefaultVal: function() {
            return getLayuiSelectValue('#brand');
        },
        getReceiveEntranceId: function() {
            return $('#receiveEntranceId').val();
        },
        getCommonRemarkList: function() {
            let remarkArr = [];
            $("input[name='commonRemark']:checked").each(function (index, item) {
                remarkArr.push({
                    id: $(item).val(),
                    name: $(item).attr("title")
                })
            });
            return remarkArr;
        },
        getExternalShopInfo: function() {
            if (!existShopSelect()) {
                return null;
            }
            let valueArr = zmnOmsSelect.getXmSelect('externalShopInfo').getValue();
            if (!valueArr) {
                return null;
            }
            if (valueArr < 1) {
                return null;
            }
            return {
                internalShopId: valueArr[0].internalShopId,
                internalShopName: valueArr[0].internalShopName,
                internalBranchShopName: valueArr[0].internalBranchShopName,
                externalShopId: valueArr[0].externalShopId
            };
        },
        getProductCateg: function() {
            if (checkEleShow("#productCategDiv")) {
                return $('input[name="productCategId"]:checked').val();
            } else {
                return null;
            }
        },
        getPhenId: function() {
            if (checkEleShow("#faultPhenDiv")) {
                return $('input[name="phenId"]:checked').val();
            } else {
                return null;
            }
        },
        getPhenName: function() {
            if (checkEleShow("#faultPhenDiv")) {
                return getLayuiRadioText('input[name="phenId"]');
            } else {
                return null;
            }
        },
        getItemId: function() {
            if (checkEleShow("#serviceItemDiv")) {
                return getLayuiSelectValue("#serviceItem");
            } else {
                return null;
            }
        },
        getQuoteProductId: function() {
            if (checkEleShow("#productNameDiv")) {
                return $('input[name="quoteProduct"]:checked').val();
            } else {
                return null;
            }
        },
        getReceiveEntranceId: function() {
            return $('#receiveEntranceId').val();
        },
        getRequestId : function () {
            return $("#requestId").val();
        },
        getReworkReasonList: function () {
            const reworkReasonList = [];
            $("input[name=reworkReasonList]:checked").map((i, e) => {
                return reworkReasonList.push($(e).val());
            });
            return reworkReasonList;
        }
    };

    function getLayuiRadioText(selector) {
        return $(selector + ":checked").prop("title");
    }

    /**
     * 设置表单字段值
     * @param {object} values 表单值对象
     */
    function setFieldsValue(values) {
        layui.form.val('zmn-order-add-form', values);
    }

    /**
     * 优惠相关
     */

    /**
     * 接收优惠批次ID集合
     */
    window.setDiscountInfo = function(obj) {
        // 获取当前手机号对应的数组（防止修改过手机号，优惠券发放给错误用户）
        let discountInfoMap = discountTelephoneMap.get(getters.getTelephone());
        if (!discountInfoMap) {
            // 当前手机号优惠信息
            discountInfoMap = new Map();
            discountTelephoneMap.set(getters.getTelephone(), discountInfoMap);
        }
        // 处理CheckBox选中值
        if (obj.sendCoupFlg) {
            obj.sendCoupFlg = 2;
        } else {
            obj.sendCoupFlg = 1;
        }

        let key = "" + obj.batchId + "-" + obj.activityId;

        discountInfoMap.set(key, obj);
    };

    /**
     * 接收优惠批次ID集合
     */
    function setBestDiscountInfo(obj) {
        // 获取当前手机号对应的数组（防止修改过手机号，优惠券发放给错误用户）
        let discountInfoMap = bestDiscountTelephoneMap.get(getters.getTelephone());
        if (!discountInfoMap) {
            // 当前手机号优惠信息
            discountInfoMap = new Map();
            bestDiscountTelephoneMap.set(getters.getTelephone(), discountInfoMap);
        }
        // 处理CheckBox选中值
        if (!obj.sendCoupFlg) {
            obj.sendCoupFlg = 2;
        }

        let key = "" + obj.batchId + "-" + obj.activityId;

        discountInfoMap.set(key, obj);
    };

    function clearCurrDiscountInfo() {
        // 获取当前手机号对应的数组（防止修改过手机号，优惠券发放给错误用户）
        let discountInfoMap = discountTelephoneMap.get(getters.getTelephone());
        if (discountInfoMap) {
            // 当前手机号优惠信息
            let discountProIdxInfoMap = new Map();

            // 刷新优惠信息
            reloadProductDiscount();
        }
    }

    function clearAllProductDiscountInfo(channelId, cityId, productId) {
        // 获取当前手机号对应的数组
        let discountInfoMap = discountTelephoneMap.get(getters.getTelephone());

        // 清空
        discountTelephoneMap.set(getters.getTelephone(), new Map());

        // 重新获取优惠
        reloadProductDiscount(channelId, cityId, productId);
    }

    function reloadProductDiscount(channelId, cityId, productId) {
        // 获取当前产品价格信息
        var price = $("#amount").data("price");
        reloadDiscountInfo(price, true, channelId, cityId, productId);
    }

    function reloadAdvanceQuoteDiscount() {
        setTimeout(function () {
            if (!checkEleShow('#quoteTypeDiv')) {
                return;
            }

            $("#discount-wrapper").show();

            // 判断当前是否需要根据报价产品生成价格
            let channelId = getters.getChannelId();
            let cityId = getters.getCityId();
            if (checkEleShow('#productNameDiv')) {
                // 显示

                // 获取当前产品价格信息
                let $product = $('input[name="quoteProduct"]:checked');
                let price = $product.data("price");

                reloadDiscountInfo(price, true, channelId, cityId);
            } else {
                // 隐藏
                reloadDiscountInfo(0, true, channelId, cityId, productId);
            }
        }, 500);
    }

    /**
     * 重新加载优惠相关信息
     */
    function resetDiscountInfoWithNoPrice(index) {
        // 隐藏勾选最大优惠 并设置checkBox为未选中
        $("#send-discount-checkbox").attr("checked", false);
        form.render();
        $("#send-discount-checkbox").parent().parent().hide();

        $("#used-discount").text("工程师确认价格后系统自动使用").parent().show();
    }

    function reloadDiscountInfo(price, isShow, channelId, cityId, productId, showType) {
        if (!price || price === 0) {
            resetDiscountInfoWithNoPrice();
            return;
        }
        // 渠道id
        if (!channelId) {
            channelId = getters.getChannelId();
            if (!channelId) {
                return;
            }
        }

        // 城市id
        if (!cityId) {
            cityId = getters.getCityId();
            if (!cityId) {
                return;
            }
        }

        // 产品id
        if (!productId) {
            productId = getters.getProductId();
            if (!productId) {
                return;
            }
        }

        // 产品类型
        if (!showType) {
            showType = getters.getProductShowType();
            if (!showType) {
                return;
            }
        }
        // 批次集合
        let batchListJson = "";
        if (discountTelephoneMap.get(getters.getTelephone())) {
            let batchList = Array.from(discountTelephoneMap.get(getters.getTelephone()).values()).map((batch) => JSON.stringify(batch));
            batchListJson = "[" + batchList.join(",") + "]";
        }
        // 查询无用户优惠信息
        $http
            .$get(GET_ADD_ORDER_DISCOUNT_URL, {
                telephone: getters.getTelephone(),
                channelId: channelId,
                cityId: cityId,
                brandId: getters.getBrandId(),
                productId: productId,
                productNum: getters.getCount(),
                showType: showType,
                bizType: getters.getBizType(),
                servItemType: $("#servItemType").val(),
                platWork: getters.getPlatWork(),
                plat: getters.getPlat(),
                type: getters.getType(),
                price: price,
                batchListJson: batchListJson,
            })
            .then(
                function(data) {
                    reloadUseDiscountInfo(data, isShow);
                    reloadMaxDiscountInfo(data, isShow);

                    // 缓存最佳优惠组合
                    if (data.bestDiscountList) {
                        var bestDiscountList = data.bestDiscountList;
                        for (let i = 0; i < bestDiscountList.length; i++) {
                            setBestDiscountInfo(bestDiscountList[i]);
                        }
                    }

                },
                function(msg) {
                    layer.msg(msg);
                }
            );
    }

    /**
     * 获取当前优惠（不发放优惠券即可使用）
     */
    function reloadUseDiscountInfo(data, isShow) {
        if (isShow) {
            $("#used-discount").text("当前优惠 -" + data.currentPreferential / 100 + "元\n 优惠后价格 " + data.afterPrice / 100 + "元").parent().show();
        } else {
            $("#used-discount").parent().hide();
        }
    }

    /**
     * 获取最大可用优惠（包含优惠券）
     */
    function reloadMaxDiscountInfo(data, isShow) {
        if (isShow && data.bestPreferential > data.currentPreferential) {
            $("#send-discount-checkbox").prop("title", "查询到最佳优惠" + data.bestPreferential / 100 + "元，优惠后价格" + data.afterBestPrice / 100 + "元，勾选后使用");
            form.render();
            // 修改字体颜色
            $("#send-discount-checkbox").parent().find("span").css("color", "red");
            $("#send-discount-checkbox").parent().parent().show();
        } else {
            $("#send-discount-checkbox").parent().parent().hide();
        }
    }

    /**
     * 渲染服务品类选择下拉框
     * @param data 下拉框数据
     */
    function renderProductSelect(data, elment) {
        var htmlStr = '<option value=""></option>';

        $.each(data, function(index, item) {
            var price = item.price || item.originalPrice;
            var productName;

            if (price) {
                productName = item.text + '_' + price + '_' + item.unit
            } else {
                productName = item.text
            }

            htmlStr += '<option value="' + item.value +
                '" data-price="' + (price ? price : '') +
                '" data-unit="' + (item.ext1 || '') +
                '" data-type="' + item.type +
                '" data-pid="' + item.pid + '">' +
                productName +
                '</option>';
        });

        $(elment).html(htmlStr);
        form.render('select');
    }

    /**
     *  初始化产品下拉框
     * @param {string} servCategId 服务分类id
     */
    function initProduct(switchShowType, selectServCategory) {
        var plat = getters.getPlat();
        var servCategId = getters.getServCategId();
        var productShowType = getters.getProductShowType();
        var cityId = getters.getCityId();
        var channelId = getters.getChannelId();
        var bizType = getters.getBizType();

        if (!plat || !productShowType || !cityId || !channelId) {
            return;
        }
        initProductSelect(plat, servCategId, productShowType, cityId, channelId, switchShowType, selectServCategory, bizType).always(function() {
            // 计算价格
            calculateProductAmount()
        })

    }

    function initDutyTime(callback) {
        if (!getters.getProductId()) {
            if (callback) callback();
            return;
        }

        var productId = getLayuiSelectValue("#product");
        var showProductId = getLayuiSelectValue("#showProduct")
        $("#gird-group-distribute-master").text('');

        $http.$get(GET_DEFAULT_DUTYTIME, {
            dutyTime: getters.getDutyTime(),
            plat: getters.getPlat(),
            platWork: getters.getPlatWork(),
            channelId: getters.getChannelId(),
            cityId: getters.getCityId(),
            productId: productId,
            showProductId: showProductId,
            type: getters.getOrderType(),
            latitude: getters.getLatitude(),
            longitude: getters.getLongitude(),
            isGrid: isGrid,
            productNum: getters.getCount(),
            servCategId: getters.getServCategId(),
            bizType: getters.getBizType(),
        }).then(function(data) {
            isAvailableWeek = data.isAvailableWeek;
            if (options.isNew) {
                if (data.girdGroupDistributeShowStr) {
                    //网格组派单结果展示回显
                    initDutyTimeInfo("", "");
                    $("#gird-group-distribute-master").text(data.girdGroupDistributeShowStr);
                } else {
                    $("#gird-group-distribute-master").text('');
                    initDutyTimeInfo(data.showDutyTime, data.dutyTime, data.isToday);
                }
            }
            if (callback) callback();
        }, function(msg) {
            layer.msg('获取默认时间失败');
            initDutyTimeInfo('', '');
            if (callback) callback();
        });
    }

    function initProductSelect(plat, servCategId, productShowType, cityId, channelId, switchShowType, selectServCategory, bizType) {
        $('#dv-show-product').removeClass('layui-hide');
        $('#dv-product').removeClass('layui-hide');

        var elment;
        var cacheData;
        var cacheKey = servCategId + '-' + cityId + '-' + channelId + '-' + bizType;

        if (productShowType == '1') {
            elment = '#product';
            $('#dv-show-product').addClass('layui-hide');
            cacheData = productCache[cacheKey];
        } else {
            elment = '#showProduct';
            $('#dv-product').addClass('layui-hide');
            cacheData = showProductCache[cacheKey];
        }

        // 记录上一次选中的值
        var perProductId = getLayuiSelectValue(elment);
        var perProductText = getLayuiSelectText(elment);

        // 前后端产品切换过来的，有值不加载数据
        if (switchShowType) {
            if (getLayuiSelectValue(elment)) {
                return $.Deferred().resolve();
            }
        }
        // 其他方式加载的，全部清空
        else {
            renderProductSelect([], '#product');
            renderProductSelect([], '#showProduct');
        }

        if (cacheData) {
            renderProductSelect(cacheData, elment);

            // 默认选中上一个产品
            $(elment).val(perProductId);
            form.render('select');

            // 如果没有合适的产品，提示 当前渠道未开通：xx产品，请重新选择产品
            if (!getLayuiSelectValue(elment) && perProductId && selectServCategory !== 1) {
                zmnUtils.layui.toastError('当前渠道未开通：' + perProductText + '，请重新选择产品');
            }

            return $.Deferred().resolve();
        } else {
            return fetchProductData(plat, servCategId, productShowType, cityId, channelId, bizType).then(function(data) {
                renderProductSelect(data, elment);

                if (productShowType == '1') {
                    productCache[cacheKey] = data;
                } else {
                    showProductCache[cacheKey] = data;
                }

                // 默认选中上一个产品
                $(elment).val(perProductId);
                form.render('select');

                if (!getLayuiSelectValue(elment) && perProductId && selectServCategory !== 1) {
                    zmnUtils.layui.toastError('当前渠道未开通：' + perProductText + '，请重新选择产品');
                }
            }, function(msg) {
                layer.msg('产品数据获取失败');
                renderProductSelect([], elment);
            })
        }
    }

    /**
     * 初始化产品数量输入框
     * @param {string} value 产品数量
     */
    function initCountInput(value, productShowType) {
        var $input = $('#count');
        $input.val(value);

        // if (productShowType) {
        //     var maxValue = productShowType === PRODUCT_SHOW_TYPE_ENUM.FRONT ? 1 : 10;
        //     $input.attr('max', maxValue);
        // }
    }

    /**
     * 初始化产品数量
     * @param {string} text 产品单位
     */
    function initProductUnit(text) {
        $('#unit').text(text);
    }

    /**
     * 初始化品牌下拉框
     * @param {string} value 初始值
     */
    function initBrandSelect(value) {
        $('#brand').val(value);
        form.render('select');
    }

    /**
     * 渲染常见错误多选框组
     * @param data 下拉框数据
     */
    function renderFaultsCheckboxGroup(data) {
        var htmlStr = '';
        var $faultsGroup = $('#faults-wrapper');
        var $faultsRow = $faultsGroup.closest('.layui-form-item');

        $.each(data, function(index, item) {
            htmlStr += '<input type="checkbox" lay-skin="primary" name="faultIdList" title="' + item.text + '" value="' + item.value + '" >';
        });

        $faultsGroup.html(htmlStr);

        if (!checkEleShow("#quoteTypeDiv") && data.length) {
            $faultsRow.show();
        } else {
            $faultsRow.hide();
        }

        form.render('checkbox');
    }

    /**
     * 初始化常见故障多选框组
     * @param {string} productId 产品id
     */
    function initCommonFaultsCheckboxGroup(productId) {
        // 判断是否需要报价，如果需要，不显示
        if (checkEleShow("#quoteTypeDiv")) {
            return;
        }
        if (!productId) {
            renderFaultsCheckboxGroup([]);
        } else {
            fetchProductSubsidiary(productId).then(function(data) {
                renderFaultsCheckboxGroup(data);
            })
        }

        initOtherFaultsTextarea('');
    }

    /**
     * 初始化其他故障文本框
     * @param {string} value 初始值
     */
    function initOtherFaultsTextarea(value) {
        $('#fault-remark').val(value);
    }

    /**
     * 更新下拉框选项的状态。1. 当前元素不可点击 2. 其余可以选项可以点击
     * @param elem select dom 元素
     */
    function updateOptionsStatus(elem) {
        $(elem).find('option')
            .attr("disabled", false)
            .filter(':selected')
            .attr("disabled", true);

        form.render('select');
    }

    /**
     * 渲染下拉选择框
     * @param el
     * @param data 下拉框数据
     * @param defaultVal 默认值
     */
    function renderSelect(el, data, defaultValue) {
        var htmlStr = '<option value=""></option>';

        $.each(data, function(index, item) {
            htmlStr += '<option value="' + item.value + '" ' + (item.value == defaultValue ? ' selected ' : '') + '>' + item.text + '</option>'
        });

        $(el).html(htmlStr);
        form.render('select');
    }

    /**
     * 渲染城市选择下拉框
     * @param {array} data 城市数据
     */
    function renderCitySelect(data) {
        var htmlStr = '<option value=""></option>';

        var oldCityId = getters.getCityId();
        var oldCityName = getLayuiSelectText("#cityId");

        $.each(data, function(index, item) {
            htmlStr += '<option value="' + item.value +
                '" data-pid="' + item.pid + '" ' +
                (oldCityId == item.value ? 'selected ' : ' ') +
                '>' + item.text + '</option>';
        });
        $('#cityId').html(htmlStr);
        form.render('select');

        var result = $.grep(data, function(e) { return e.value == oldCityId; });
        if (showCheckCityMsg && options.isNew && oldCityName != '' && oldCityName != '市' && result.length == 0) {
            // 若未开通，清空：地址
            var cityName = getLayuiSelectText("#cityName");
            clearAddress();
            zmnUtils.layui.toastError('当前渠道未开通：' + oldCityName + '，请重新选择城市');
        }
    }

    /**
     * 渲染城市选择下拉框
     * @param provinceId 省份ID
     */
    function initCitySelect(provinceId, channelId, showMsg, cb) {
        showCheckCityMsg = showMsg;

        var key = provinceId;
        if (options.isNew) {
            key = (provinceId || 0) + '-' + channelId;
        } else {
            // provinceId 为空时执行
            if (!provinceId) {
                renderCitySelect(json.cityList);
                if (cb) {
                    cb();
                }
                return;
            }
        }

        if (cityData[key]) {
            renderCitySelect(cityData[key]);
        } else {
            fetchCityData(provinceId).done(function(data) {
                cityData[key] = data;
                renderCitySelect(data);
                if (cb) {
                    cb();
                }
            });
        }
    }

    /**
     * 初始化服务区域显示
     * 初始化区县下拉框
     * @param {array} data 服务区域列表
     */
    function renderServiceArea(data, cb) {
        var htmlStr = '';
        countyData = [];
        $.each(data, function(index, county) {
            if (!county.disabled) {
                htmlStr += `<span class="county" data-id="${county.value}">${county.text}</span>`;
                countyData.push({
                    countyId: county.value,
                    countyName: county.text
                })
            }
        });
        var $serviceArea = $('#county-list');

        $serviceArea.html(htmlStr);

        var $countyId = $('#countyId');
        var optionHtmlStr = '<option value="">请选择区县</option>';

        var countyId = $countyId.val();
        $.each(data, function(index, county) {
            if (!county.disabled) {
                if (countyId && county.value == countyId) {
                    optionHtmlStr += `<option value="${county.value}" selected="selected">${county.text}</option>`;
                } else {
                    optionHtmlStr += `<option value="${county.value}">${county.text}</option>`;
                }
            }
        });

        $countyId.html(optionHtmlStr);
        form.render('select');

        if (data.length) {
            $serviceArea.show();
        } else {
            $serviceArea.hide();
        }

        if (typeof cb === 'function') {
            cb();
        }

        updateAreaList(getters.getCountyId());
    }

    /**
     *校验渠道 选择外部店铺
     * @param cityId 城市 id
     */
    function checkSelectExternalShop(channelId, cityId) {

        if (!existShopSelect()) {
            return;
        }

        // 修改页面不必填
        if (options.isUpdate) {
            $('#externalShopInfoSelelct').attr('lay-verify', '');
            $('#externalShopLabel').removeClass('layui-form-required');
            return;
        }

        if (!channelId) {
            $('#externalShopInfoSelelct').attr('lay-verify', '');
            $('#externalShopLabel').removeClass('layui-form-required');
            return;
        }

        $http.get(GET_CHANNEL_CONF_URL, {channelId: channelId}).then(
            function (data) {
                if (data.selectMarketingShop == 2) {
                    $('input[name="externalShopInfoSelelct"]').attr('lay-verify', 'required')
                    $('#externalShopLabel').addClass('layui-form-required');
                } else {
                    $('input[name="externalShopInfoSelelct"]').attr('lay-verify', '');
                    $('#externalShopLabel').removeClass('layui-form-required');
                }
            },
            function () {
                $('input[name="externalShopInfoSelelct"]').attr('lay-verify', '');
                $('#externalShopLabel').removeClass('layui-form-required');
            }
        );
    }

    /**
     * 初始化街道显示
     */
    function renderStreetIdSelect(data, cb) {
        var optionHtmlStr = '<option value="">请选择乡镇或街道</option>';

        var streetId = $('#streetId').val();
        $.each(data, function(index, street) {
            optionHtmlStr += `<option value="${street.areaId}" data-longitude="${street.longitude}" data-latitude="${street.latitude}">${street.name}</option>`;
        });

        $('#streetId').html(optionHtmlStr);
        form.render('select');

        if (typeof cb === 'function') {
            cb();
        }
    }

    /**
     * 初始化服务区域显示
     */
    function initServiceArea(cityId, cb) {
        var cityId = cityId || getters.getCityId();

        if (!cityId) {
            renderServiceArea([]);
            return;
        }

        fetchAreaData(cityId).done(function(data) {
            renderServiceArea(data, cb);
        });
    }

    /**
     *  生成街道地址下拉框列表项
     * @param {Object} data 街道地址数据
     * @returns {string}
     */
    function createfetchSuggestedItemHtmlStr(data) {
        data.district = data.district || '';
        return '<li data-lng="' + data.location.lng +
            '" data-lat="' + data.location.lat +
            '" data-communityid="' + (data.communityId || 999999) +
            '" data-source="' + (data.source || 2) +
            '" data-city="' + data.city +
            '" data-district="' + data.district +
            '" data-name="' + data.name +
            '">' + data.name +
            '<span class="city-district">' + data.city + data.district + '</span>' +
            '</li>';
    }

    /**
     *  渲染街道列表下拉框
     * @param params 联想参数
     */
    function renderStreetSelect(params) {
        $('#suggestPanel ul').html('<li class="loading tip">加载中</li>');
        fetchSuggestedStreet(params, function(data) {
            var htmlStr = '';

            if (data.length) {
                $.each(data, function(index, item) {
                    htmlStr += createfetchSuggestedItemHtmlStr(item);
                });
            } else {
                htmlStr += '<li class="non-data tip">无匹配项</li>';
            }

            layer.open({
                area: ['0', '0'],
                shade: [0.1, '#fff'],
                offset: ['100000px', '100000px'],
                scrollbar: false,
                zIndex: 888,
                success: function(layero, index) {
                    $('#layui-layer-shade').on('click', function() {
                        $(layero).find('.layui-layer-close').trigger('click');
                    });
                    $('.layui-layer-shade').on('click', function() {
                        layer.closeAll();
                        $('#customerAddress').val('')
                        $('#suggestPanel').hide();
                    })
                },
                cancel: function() {
                    $('#suggestPanel').hide();
                    clearAddress();
                }
            });
            $('#suggestPanel ul').html(htmlStr);
            $('#suggestPanel').show();
            // form.render('select');

            // $('#street-wrapper').find('.layui-form-select').addClass('layui-form-selected');
            // $('#street-wrapper').find('input').val(queryText).focus();
        });
    }

    /**
     * 渲染服务类型选择下拉框
     */
    function renderServCategorySelect(callback) {
        var cityId = getters.getCityId();
        var channelId = getters.getChannelId();
        var showType = getters.getProductShowType();
        var servCategId = getters.getServCategId();
        if (!cityId || !channelId) {
            return;
        }

        var cacheKey = cityId + '-' + channelId + '-' + showType;
        if (servCategoryCache[cacheKey]) {
            renderSelect('#servCategoryId', servCategoryCache[cacheKey], servCategId);
            // 加载产品
            if (callback) {
                callback();
            }
        } else {
            $.getJSON(GET_SERV_CATEG_BY_CITY_CHANNEL_SHOWTYPE_URL, {
                    channelId: channelId,
                    cityId: cityId,
                    showType: showType
                },
                function(rsp) {
                    if (rsp.status === 200) {
                        servCategoryData = rsp.data;
                        servCategoryCache[cacheKey] = servCategoryData;
                        renderSelect('#servCategoryId', servCategoryData, servCategId);
                    } else {
                        renderSelect('#servCategoryId', []);
                    }
                    // 加载产品
                    if (callback) {
                        callback();
                    }
                });
        }
    }

    /**
     * 渲染品牌选择下拉框
     * @param data 下拉框数据
     */
    function renderBrandSelect($productWrapper) {
        if (brandData) {
            renderSelect($productWrapper.find('.brand-select'), brandData);
        } else {
            $.getJSON(BRAND_URL, function(rsp) {
                if (rsp.status === 200) {
                    brandData = rsp.data;
                    renderSelect($productWrapper.find('.brand-select'), rsp.data);
                } else {
                    renderSelect($productWrapper.find('.brand-select'), []);
                }
            });
        }
    }

    /**
     * 设置分公司名
     * @param {string} name 公司名
     */
    function setCompanyInfo(name) {
        $('#company').html(name);
    }

    /**
     * 校验提前付试点
     */
    function checkAdvanceQuote() {
        let cityId = getters.getCityId();
        let servCategId = getters.getServCategId();
        let productId = getters.getProductId();
        let showProductType = getters.getProductShowType();

        if (!cityId || !productId || !showProductType) {
            hideAllAdvanceQuoteItem();
            return;
        }

        $http.$post(
            CHECK_ADVANCE_QUOTE_URL, {
                cityId: cityId,
                servCategId: servCategId,
                productId: productId,
                showProductType: showProductType,
            }).then(function (rsp) {
                // 请求成功, 2 开启试点
                let isAdvanceQuote = rsp == 2;
                // 初始化报价试点
                initAdvanceQuote(isAdvanceQuote);
            }
        );
    }

    /**
     * 初始化之后校验提前付试点
     */
    function initCheckAdvanceQuote() {
        if (checkEleShow("#quoteTypeDiv")) {
            return;
        }
        checkAdvanceQuote();
    }

    /**
     * 初始化报价试点
     */
    function initAdvanceQuote(isAdvanceQuote) {
        $('input[name=quoteType][value="1"]').removeAttr("disabled");
        $('input[name=quoteType][value="2"]').removeAttr("disabled");
        if (isAdvanceQuote) {

            let showType = getters.getProductShowType();
            if (showType == '1') {
                layer.msg("此产品符合提前付试点，请选择前台产品");
                form.render();
                return;
            }

            // 是报价试点，如果是前台产品 只禁用后台产品
            $('input[name=productShowType][value="1"]').attr("disabled", "disabled");
            if (getters.getProductShowType() == '1') {
                // 切换到选择前台产品，并且禁用后台产品按钮
                $('input[name=productShowType][value="2"]').prop("checked", "true");
                triggerLayuiEvent('input[name=productShowType][value=2]', 'product-showtype');
                setTimeout(function (params) {
                    layer.msg("试点城市，仅支持选择前台产品");
                }, 500);
            }
            $("#amount-wrapper").hide();
            $("#faultDiv").hide();
            $(".otherFault").hide();
            // 隐藏新增产品按钮
            $("#addProduct").hide();
            // 显示报价方式选择框
            $("#quoteTypeDiv").show();
            // 显示发送短信按钮
            $("#sendOrderTransferFailMessageBtn").show();
            $("#sendOrderConfirmQuotedFailMessageBtn").show();
            // 特殊提示信息
            $("#multiServiceItem").hide();

            // 初始化报价相关信息
            initAdvanceQuoteItem();
        } else {
            // 启用后台产品
            $('input[name=productShowType][value="1"]').removeAttr("disabled");
            // 显示新增产品按钮
            $("#addProduct").show();
            // 隐藏发送短信按钮
            $("#sendOrderTransferFailMessageBtn").hide();
            $("#sendOrderConfirmQuotedFailMessageBtn").hide();
            // 隐藏报价相关元素
            hideAllAdvanceQuoteItem();
            // 故障、其他故障

            if ($("faults-wrapper").html()) {
                $("#faultDiv").show();
            }
            $(".otherFault").show();

        }

        // 刷新价格表
        loadAdvanceQuotePriceTable();

        form.render();
    }

    /**
     * 触发layui form.on事件
     */
    function triggerLayuiEvent(jqueryFilter, filter) {
        var elem = layui.$(jqueryFilter);
        var option = {
            elem:elem,
            value: elem.val(),
            othis: elem.next('layui-form-radio')
        }
        //layui.event(modName, events, params)	执行自定义模块事件，搭配 onevent 使用
        layui.event('form', 'radio('+ filter +')', option);
    }

    // 初始化报价相关内容
    function initAdvanceQuoteItem() {
        let cityId = getters.getCityId();
        let channelId = getters.getChannelId();
        let bizType = getters.getBizType();
        let productId = getters.getProductId();
        let platWork = getters.getPlatWork();
        let brandId = getters.getBrandIdWithoutDefaultVal();
        if (!cityId || !channelId || !productId || !brandId) {
            hideAllAdvanceQuoteItem();
            return;
        }

        // 获取报价相关信息
        $.ajax({
                url: GET_QUOTE_INFO_URL,
                type: "POST",
                data: JSON.stringify({
                    bizType: bizType,
                    channelId: channelId,
                    platWork: platWork,
                    cityId: cityId,
                    showProductId: productId
                }),
                processData: false,
                contentType: "application/json;charset=UTF-8",
                error: function () {
                    alert('获取信息失败');
                },
                success: function (rsp) {
                    if (rsp.status === 200) {
                        // 请求成功
                        let quoteInfo = rsp.data;
                        let brandId = getters.getBrandIdWithoutDefaultVal();
                        // 是否指定了使用某个报价信息
                        if (quoteInfo.faultPhenList) {
                            // 所有报价方式均可用，默认故障现象报价
                            $('input[name="quoteType"][value="1"]').removeAttr("disabled");
                            $('input[name="quoteType"][value="1"]').prop("checked", "true");
                            if (brandId) {
                                initFaultPhenList(quoteInfo.faultPhenList);
                            }
                        } else {
                            // 服务项报价
                            $('input[name="quoteType"][value="1"]').prop("disabled", "disabled");
                            $('input[name="quoteType"][value="2"]').prop("checked", "true");
                            if (brandId) {
                                initServiceItemList(quoteInfo.itemList);
                            }
                        }

                    }
                }
            }
        );
    }

    function initFaultPhenList(data) {
        let optionHtmlStr = "";
        var isChecked = data.length <= 1;
        let value ;
        $.each(data, function (index, phen) {
            value = phen.value;
            optionHtmlStr += `<input type="radio" lay-skin="primary" name="phenId"  value="${phen.value}" title="${phen.text}"`;
            if(isChecked) {
                optionHtmlStr += ` checked `;
            }
            optionHtmlStr += `lay-filter="faultPhen"/>`;
        });

        $("#faultPhen").html(optionHtmlStr);
        form.render();

        $("#serviceItemDiv").hide();
        $("#faultPhenDiv").show();
        $("#productCategDiv").hide();
        $("#productNameDiv").hide();

        if(isChecked && value) {
            triggerLayuiEvent('input[name=phenId][value='+ value +']', 'faultPhen');
        }
    }
    function initServiceItemList(data) {
        var optionHtmlStr = '<option value="">请选择服务项目</option>';

        $.each(data, function(index, item) {
            optionHtmlStr += `<option value="${item.value}">${item.text}</option>`;
        });


        $("#serviceItem").html(optionHtmlStr);
        form.render();

        $("#serviceItemDiv").show();
        $("#faultPhenDiv").hide();
        $("#productCategDiv").hide();
        $("#productNameDiv").hide();
    }

    function initProductCateg(data) {
        if (data.length <= 0) {
            $("#productCategDiv").hide();
            $("#productNameDiv").hide();
            return;
        }
        var optionHtmlStr = "";
        var isChecked = data.length <= 1;
        let value ;
        $.each(data, function(index, categ) {
            let title = categ.categName + "  /  " + categ.minPrice / 100 + " ~ " + categ.maxPrice /100 + " 元";

            value = categ.categId;
            optionHtmlStr += ` <input type="radio"
                                    style="width:100%;"
                                           gotype="index"
                                           name="productCategId"
                                           value="${categ.categId}"
                                           title="${title}"`;
            if(isChecked) {
                optionHtmlStr += ` checked `;
            }
            optionHtmlStr +=`lay-filter="productCateg">`;
        });

        $("#productCateg").html(optionHtmlStr);
        form.render();

        $("#productCategDiv").show();
        $("#productNameDiv").hide();

        if(isChecked && value) {
            triggerLayuiEvent('input[name=productCategId][value='+ value +']', 'productCateg');
        }
    }
    function initQuoteProduct(data) {
        var optionHtmlStr = "";
        var isChecked = data.length <= 1;
        $.each(data, function(index, product) {
            let title = product.tariffName + "  /  " + product.price / 100 + " 元";

            optionHtmlStr += ` <input type="radio"
                                    style="width:100%;"
                                           gotype="index"
                                           name="quoteProduct"
                                           value="${product.productId}"
                                           title="${title}"
                                           data-item-id="${product.itemId}"
                                           data-price="${product.price}"`;
            if(isChecked) {
                optionHtmlStr += ` checked `;
            }
            optionHtmlStr +=`lay-filter="quoteProduct">`;
        });

        $("#quoteProduct").html(optionHtmlStr);
        form.render();

        $("#productNameDiv").show();

        if (data.length === 1) {
            triggerLayuiEvent('input[name="quoteProduct"]:checked', 'quoteProduct');
        }
    }

    /**
     * 获取服务项
     * @param phenId
     * @param itemId
     */
    function fetchProductCateg(phenId, itemId) {
        if (!phenId && !itemId) {
            $("#productCategDiv").hide();
            $("#productNameDiv").hide();
            return;
        }
        let cityId = getters.getCityId();
        let channelId = getters.getChannelId();
        let servCategId = getters.getServCategId();
        let bizType = getters.getBizType();
        let productId = getters.getProductId();
        let platWork = getters.getPlatWork();
        let brandId = getters.getBrandIdWithoutDefaultVal();
        if (!cityId || !channelId || !servCategId || !productId || !brandId) {
            return;
        }

        let requestUrl;
        let data = {
            bizType: bizType,
            channelId: channelId,
            platWork: platWork,
            cityId: cityId,
            showProductId: productId,
            itemId: itemId,
            brandId: brandId
        };
        if (phenId) {
            data.phenId = phenId;
            requestUrl = LIST_PRODUCT_CATEG_WITH_PHEN_ID_URL;
        } else if (itemId){
            data.itemId = itemId;
            requestUrl = LIST_PRODUCT_CATEG_WITH_ITEM_ID_URL;
        } else {
            return;
        }

        // 服务项获取产品二级分类
        $.ajax({
                url: requestUrl,
                type: "POST",
                data: JSON.stringify(data),
                processData: false,
                contentType: "application/json;charset=UTF-8",
                error: function () {
                    alert('获取信息失败');
                },
                success: function (rsp) {
                    if (rsp.status === 200) {
                        // 请求成功
                        if (rsp.data) {
                            initProductCateg(rsp.data);
                        }

                    }
                }
            }
        );
    }

    function loadAdvanceQuotePriceTable() {
        setTimeout(function () {
            var cityId = getters.getCityId();
            var productShowType;
            productId = getters.getProductId();
            productShowType = getters.getProductShowType();
            var channelId = getters.getChannelId();
            var bizType = getters.getBizType();
            var type = getters.getType();
            var plat = getters.getPlat();
            var brandId = getters.getBrandIdWithoutDefaultVal();

            if (!channelId || !cityId || !productId || !brandId) {
                $("#advanceQuotePrice").hide();
                return;
            }
            let productCategId = getters.getProductCateg();
            let itemId = getters.getItemId();
            let phenId = getters.getPhenId();
            let phenName = getters.getPhenName();

            if (!itemId && !phenId) {
                $("#advanceQuotePrice").hide();
                return;
            }
            $("#advanceQuotePrice").show();

            let priceTableURL;
            if (phenId) {
                let showProductId = getters.getProductId();
                let backProductId = getters.getQuoteProductId();
                priceTableURL = zmnUtils.serializeURL(ADVANCE_PRODUCT_PHEN_PRICE_TABLE_URL, {
                    cityId: cityId,
                    productId: showProductId,
                    channelId: channelId,
                    bizType: bizType || 1, // 默认保外
                    brandId: brandId,
                    tariffType: productShowType,
                    type: type,
                    plat: plat,
                    categId: productCategId,
                    phenId: phenId,
                    backProductId: backProductId
                });
                priceTableURL += "&phenName=" + phenName;
            } else {
                // 判断是否已选后台产品，如果已选择，覆盖为后台产品
                if (checkEleShow("#productNameDiv")
                    && $('input[name="quoteProduct"]:checked').val()) {
                    productId = $('input[name="quoteProduct"]:checked').val();
                    productShowType = 1;
                }
                priceTableURL = zmnUtils.serializeURL(ADVANCE_PRODUCT_PRICE_TABLE_URL, {
                    cityId: cityId,
                    productId: productId,
                    channelId: channelId,
                    bizType: bizType || 1, // 默认保外
                    brandId: brandId,
                    tariffType: productShowType,
                    type: type,
                    plat: plat,
                    itemId: itemId,
                    categId: productCategId
                });
            }

            $("#advanceQuotePriceTable").prop("src", priceTableURL);
        }, 500);

    }
    // 隐藏提前报价相关显示框
    function hideAllAdvanceQuoteItem() {
        $("#quoteTypeDiv").hide();
        $("#serviceItemDiv").hide();
        $("#faultPhenDiv").hide();
        $("#productCategDiv").hide();
        $("#productNameDiv").hide();
    }

    // 检验某个元素是否显示
    function checkEleShow(filter) {
        return $(filter).length > 0 && $(filter).css("display") != "none";
    }

    function initAdvanceQuoteEvent() {
        form.on("radio(quoteType)", function (data) {
            let cityId = getters.getCityId();
            let channelId = getters.getChannelId();
            let servCategId = getters.getServCategId();
            let bizType = getters.getBizType();
            let productId = getters.getProductId();
            let platWork = getters.getPlatWork();
            let quoteType = data.value;
            let brandId = getters.getBrandIdWithoutDefaultVal();
            if (!cityId || !channelId || !servCategId || !productId) {
                // 隐藏下级元素
                $("#serviceItemDiv").hide();
                $("#faultPhenDiv").hide();
                $("#productCategDiv").hide();
                $("#productNameDiv").hide();
                if(!brandId) {
                    layer.msg('请选择品牌');
                }
                return;
            }

            let requestURL = "";
            let callback ;
            if (quoteType == "1") {
                // 故障现象报价
                requestURL = LIST_PHEN_URL;
                callback = function (data) {
                    initFaultPhenList(data);
                }
            } else {
                // 服务项报价
                requestURL = LIST_SERVICE_ITEM_URL;
                callback = function (data) {
                    initServiceItemList(data);
                }
            }

            // 服务项获取产品二级分类
            $.ajax({
                    url: requestURL,
                    type: "POST",
                    data: JSON.stringify({
                        bizType: bizType,
                        channelId: channelId,
                        platWork: platWork,
                        cityId: cityId,
                        showProductId: productId,
                        brandId: brandId
                    }),
                    processData: false,
                    contentType: "application/json;charset=UTF-8",
                    error: function () {
                        alert('获取信息失败');
                    },
                    success: function (rsp) {
                        if (rsp.status === 200) {
                            // 请求成功
                            callback(rsp.data);
                        } else {
                            layer.msg(rsp.message);
                        }
                    }
                }
            );

            // 初始化价格表
            loadAdvanceQuotePriceTable();
        });
        form.on("select(serviceItem)", function (data) {
            let itemId = data.value;
            fetchProductCateg(null, itemId);

            // 初始化价格表
            loadAdvanceQuotePriceTable();
            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();
        });
        form.on("radio(faultPhen)", function (data) {
            let phenId = data.value;
            if (phenId == specialFaultPhenId) {
                initProductCateg([]);

                // 显示特殊故障提示信息
                if (!checkEleShow("#specialFaultPhenTip")) {
                    let tipInfo = `<div class="layui-input-inline layui-inline-text"  style="color:red" id="specialFaultPhenTip"><span>特殊故障需使用 服务项目报价 ，如更换电视屏幕、控制板、压缩器、等故障，详见下图全部特殊故障；</span></div>`;
                    $("#faultPhen").append(tipInfo);
                }
            } else {
                fetchProductCateg(phenId, null);

                $("#specialFaultPhenTip").remove();
            }

            // 初始化价格表
            loadAdvanceQuotePriceTable();

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();
        });
        form.on("radio(productCateg)", function (data) {
            var cityId = getters.getCityId();
            var channelId = getters.getChannelId();
            var showType = 1;
            var servCategId = getters.getServCategId();
            var bizType = getters.getBizType();
            var productId = getters.getProductId();
            var platWork = getters.getPlatWork();
            let brandId = getLayuiSelectValue("#brand");
            if (!cityId || !channelId || !servCategId || !productId || !brandId) {
                return;
            }
            let categId = data.value;

            let itemId = getters.getItemId();
            let phenId = getters.getPhenId();
            // 二级分类获取产品
            let requestURL = "";
            let phenDisplay = $("#faultPhenDiv").css("display");
            if (phenDisplay != "none") {
                // 故障现象获取产品
                requestURL = LIST_PRODUCT_WITH_PHEN_URL;
            } else {
                // 服务项目获取产品
                requestURL = LIST_PRODUCT_WITH_ITEM_URL;
            }

            $.ajax({
                    url: requestURL,
                    type: "POST",
                    data: JSON.stringify({
                        bizType: bizType,
                        channelId: channelId,
                        platWork: platWork,
                        cityId: cityId,
                        showProductId: productId,
                        itemId: itemId,
                        categId: categId,
                        phenId: phenId,
                        brandId: brandId
                    }),
                    processData: false,
                    contentType: "application/json;charset=UTF-8",
                    error: function () {
                        alert('获取信息失败');
                    },
                    success: function (rsp) {
                        if (rsp.status === 200) {
                            // 请求成功
                            if (rsp.data) {
                                initQuoteProduct(rsp.data);
                            }
                        }
                    }
                }
            );

            // 初始化价格表
            loadAdvanceQuotePriceTable();

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();
        });
        form.on("radio(quoteProduct)", function (data) {

            let productId = data.value;
            // 初始化价格表
            loadAdvanceQuotePriceTable();

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();

            // 重新设置价格信息
            if (checkEleShow('#productNameDiv')) {
                // 显示

                // 获取当前产品价格信息
                let $product = $('input[name="quoteProduct"]:checked');
                let price = $product.data("price");

                let productNum = getters.getCount();

                var str = price / 100 + "" + "元";
                $("#amount").text(str).data("price", price);

                // 总价
                let totalStr = price * productNum / 100 + "" + "元";
                $("#totalAmount").text(totalStr).data("price", price);
            }
        });
    }

    //检查报价信息是否完整
    function checkQuoteInfo(data, index) {
        if (!data.quoteType) {
            return "请选择报价方式";
        }
        if (data.quoteType == "1" && !data.phenId) {
            return "请选择故障现象";
        }
        if (data.quoteType == "2" && !data.itemId) {
            return "请选择服务项";
        }
        if (!data.productCategId) {
            return "请选择产品类别";
        }
        if (!data.quoteProduct) {
            return "请选择产品型号";
        }
        return undefined;
    }

    /**
     * 初始公司信息
     */
    function initCompanyInfo() {
        // 是否平台
        if (isGrid) {
            return;
        }

        var plat = getters.getPlatWork();
        var servCategId = getters.getServCategId();
        var channelId = getters.getChannelId();
        var cityId = getters.getCityId();
        var type = getters.getOrderType();
        var dutyTime = getters.getDutyTime();
        var workId = getters.getWorkId();

        var bizType = getters.getBizType();
        var productShowType = getters.getProductShowType();
        var productId = getters.getProductId();
        var longitude = getters.getLongitude();
        var latitude = getters.getLatitude();
        var streetSource = getters.getStreetSource();

        // 返修单修改，不初始化公司信息
        if (!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
            setCompanyInfo($('#hidCompany').val());
            return;
        }

        if (!plat || !productId || !longitude || !latitude) {
            setCompanyInfo('');
        } else {
            fetchCompanyName(plat, channelId, cityId, type, dutyTime, workId, bizType, servCategId, productShowType, productId, longitude, latitude, streetSource).then(function(res) {
                if (!res) {
                    setCompanyInfo('<span style="color: red">当前平台无法服务</span>')
                    $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                } else if (res.data == 0 || res.data == 4) { // 所有平台都无法服务
                    setCompanyInfo('<span style="color: #FF0000">' + res.message + '</span>')
                    $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                } else if (res.data == 1) { // 单个服务
                    let message = res.message.split("-");
                    $("#preManageCompanyId").val(message[0]);
                    $("#preManageCompanyName").val(message[1]);
                    setCompanyInfo(message[1] || '')
                    $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                } else if (res.data == 2) {
                    // 多个服务商
                    $("#preManageCompanyId").val(0);
                    setCompanyInfo(res.message || "");
                    $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                } else {
                    setCompanyInfo(res.message || '')
                    $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                }
            });
        }
    }

    /**
     * 初始化预约时间相关时间
     * @param {string} time 时间
     */
    function initDutyTimeInfo(showTime, time, isToday) {
        $('#duty-time-input').val(time);
        $('#duty-time').text(showTime);
        if (isToday != undefined && !isToday) {
            $("#duty-time").addClass('text-red');
        } else {
            $("#duty-time").removeClass('text-red');
        }
    }

    /**
     * 计算产品价格
     */
    function calculateProductAmount() {
        // 录入手机单不展示价格表
        if (options.isEntrust === true) {
            return;
        }

        var type = $('input[name="type"]:checked').val();
        var servCategId = getters.getServCategId();

        var count = getters.getCount();
        var cityId = getters.getCityId();
        var productId = getters.getProductId();
        var channelId = getters.getChannelId();
        var bizType = getters.getBizType();
        var brandId = getters.getBrandId();

        if ((!type && !servCategId) || !count || !cityId || !productId || !channelId) {
            $('#amount-wrapper').hide();
            $("#discount-wrapper").hide();
            $("#max-discount-div").hide();
            $('#amount').val('');
            return;
        }

        $("#discount-wrapper").show();


        showToatlAmountDiv(type, servCategId, count, cityId, productId, channelId, bizType);

        // 判断是否需要报价，如果需要，不显示
        if (checkEleShow("#quoteTypeDiv")) {
            return;
        }

        $('#amount-wrapper').show();

    }

    var formUtils = {
        normalizeDutyTime: function(dateStr) {
            return util.toDateString(new Date(dateStr));
            // return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss');
        },
        normalizeFaults: function(data) {
            var faultArray = data.filter((item) => {
                return item.name === 'faultIdList';
            }).reduce((acc, curr) => {
                acc.push(curr.value);
                return acc;
            }, []);

            return faultArray;
        },
        _emptyValueFilter: function(data) {
            var params = {};

            Object.keys(data).forEach((key) => {
                if (data[key] == null || data[key] === '') {
                    return;
                }
                params[key] = data[key];
            });

            return params;
        },
        normalize: function(data) {
            var params = {};
            var excludeArr = ['faultIdList', 'productId', 'brandId', 'number', 'faultRemark',"commonRemark"];

            var field = data.field;
            var formData = $(data.form).serializeArray();

            // 如果streetid为null 就把queryCommunity 接口里的 communityId 赋值给 streetId
            if (!field.streetId) {
                field.streetId = $('#communityId').val();
            }

            Object.keys(field).forEach((key) => {
                if (excludeArr.indexOf(key) === -1) {
                    params[key] = field[key];
                }
            });

            if (!field.brandId) {
                field.brandId = $('#brand option:contains("其他")').val();
            }

            if (field.nextContactDate) {
                params.nextContactTime = field.nextContactDate + ' ' + field.nextContactTime;
            }
            console.log(params)
            let orderProduct = {
                brandId: field.brandId,
                productId: field.productId || 0,
                showProductId: field.showProductId || 0,
                productShowType: field.productShowType || 0,
                number: field.number,
                remark: field.faultRemark,
                faultIdList: this.normalizeFaults(formData),
                sendDiscountFlag: field["sendDiscountFlag"],
            };

            // 处理提前报价逻辑
            if (checkEleShow("#quoteTypeDiv")) {
                let result = checkQuoteInfo(field);
                if (result) {
                    layer.alert(result);
                    ischeck = false;
                    return;
                }
                let itemId = $('input[name="quoteProduct"]:checked').data("item-id");
                let phenId = getters.getPhenId();
                let phenName = getters.getPhenName();
                let advanceQuote = {
                    quoteType: field.quoteType,
                    phenId: phenId,
                    phenName: phenName,
                    itemId: itemId,
                    productCateg: field.productCategId
                };
                orderProduct.advanceQuote = advanceQuote;
                orderProduct.productId = field.quoteProduct;
                orderProduct.productShowType = 1;
            }

            // 处理优惠券 如果需要发放并且有的话
            let discountMap = new Map();
            let realTelephone = getters.getTelephone();
            if (discountTelephoneMap.get(realTelephone)) {
                discountMap = discountTelephoneMap.get(realTelephone);
            }
            // 最佳优惠 如果勾选了，一起发放
            if (orderProduct.sendDiscountFlag === 'on' && bestDiscountTelephoneMap.get(realTelephone)) {
                let bestDiscountMap = bestDiscountTelephoneMap.get(realTelephone);
                for (let key of bestDiscountMap.keys()) {
                    discountMap.set(key, bestDiscountMap.get(key));
                }
            }

            orderProduct.waitSendDiscountList = Array.from(discountMap.values());

            params.orderProductList = [orderProduct];

            if (params.dutyTime) {
                params.dutyTime = this.normalizeDutyTime(params.dutyTime);
            }

            // 返修备注
            if (checkEleShow("#rework-reason")) {
                params.reworkReasonList = getters.getReworkReasonList();
            }

            // 常见备注
            params.commonRemarkList = getters.getCommonRemarkList();
            // 外部店铺信息
            params.externalShopInfo = getters.getExternalShopInfo();

            return this._emptyValueFilter(params);
        }
    }

    /**
     * 判断是否是计价器类型的工单，如果是，显示amount-fault如果不是，显示amount-others
     */
    function showToatlAmountDiv(type, servCategId, count, cityId, productId, channelId, bizType) {
        var plat = getters.getPlatWork();
        var type = getters.getOrderType();
        var orderId = options.isUpdate ? getters.getOrderId() : null;
        var workId = options.isUpdate ? getters.getWorkId() : null;
        var params = {
            cityId: cityId,
            productId: productId,
            channelId: channelId,
            bizType: bizType,
            plat: plat,
            productShowType: getters.getProductShowType(),
            brandId: getters.getBrandId(),
            type: type,
            orderId: orderId,
            workId: workId
        };

        // 目前只支持啄木鸟
        $http.$get(GET_SERVITEM_TYPE_INFO_WORK_URL, params).done(function(data) {
            // 计价器类型工单
            $('#servItemType').val(data.servItemType);
            if (type == '2') {
                $('#amount-others').hide();
                $('#amount-quotation').hide();
                $('#amount-advance-pay').hide();
                $('#amount-quotation-three').hide();
            } else {
                if (data.servItemType == "1") {
                    $("#amount-others").show();
                    $("#amount-quotation").hide();
                    $("#amount-advance-pay").hide();
                    $("#amount-quotation-three").hide();
                } else if (data.servItemType == "2") {
                    $("#amount-others").hide();
                    $("#amount-advance-pay").hide();
                    $("#amount-quotation-three").hide();
                    $("#amount-quotation").show();
                } else if (data.servItemType == "3") {
                    $("#amount-others").hide();
                    $("#amount-advance-pay").show();
                    $("#amount-quotation-three").hide();
                    $("#amount-quotation").hide();
                } else if (data.servItemType == "4" || data.servItemType == "5") {
                    $("#amount-others").hide();
                    $("#amount-advance-pay").hide();
                    $("#amount-quotation").hide();
                    $("#amount-quotation-three").show();
                    var str = '';
                    if (data.servItemType == "4") {
                        str = '计价器3.0';
                    } else if (data.servItemType == "5") {
                        str = '一口价';
                    }
                    if (zmnUtils.isNumber(data.price)) {
                        str += '订单，收费为' + data.price / 100 + '元起，具体费用工程师上门检测后确定';
                    } else {
                        str += '订单，具体费用工程师上门检测后确定';
                    }
                    $('#amount-quotation-three-text').text(str);
                }
            }

            // 产品数量
            let productNum = getters.getCount();

            if (data.isShow === 1) {
                $('#amount-detail').hide();
            } else if (zmnUtils.isNumber(data.price) && data.unit) {
                $('#amount-detail').show();
                var str = data.price / 100 + '' + '元/' + data.unit;
                $('#amount').text(str).data("price", data.price);

                // 总价
                let totalStr = data.price * productNum / 100 + "" + "元";
                $("#totalAmount").text(totalStr).data("price", data.price);
            } else if (zmnUtils.isNumber(data.price)) {
                $('#amount-detail').show();
                var str = data.price / 100 + '' + '元';
                $('#amount').text(str).data("price", data.price);

                // 总价
                let totalStr = data.price * productNum / 100 + "" + "元";
                $("#totalAmount").text(totalStr).data("price", data.price);
            } else {
                $('#amount-detail').hide();
            }

            var isShow = data.isShow !== 1;
            reloadDiscountInfo(data.price, isShow);

            // 新单，非计价器产品，有多个后台产品时数量必须为1，其它可大于1
            if (type == '1' && data.isShow === 2 && !isQuotation(data.servItemType)) {
                maxProductCount = 10;
            } else {
                maxProductCount = 1;
            }
        }).fail(function(msg) {
            layer.msg(msg);
        });

    }

    /**
     * 省份选择下拉框选中事件处理函数
     * @param provinceId 省份 id
     */
    function handleProvinceSelect(provinceId) {
        // 更新下拉框选项状态
        updateOptionsStatus($('#provinceId'));

        // 渲染城市下拉框
        initCitySelect(provinceId, getters.getChannelId(), false);

        // 清空区域列表
        renderServiceArea([]);

        // 清空街道信息
        renderStreetIdSelect([]);

        // 清空地址
        clearAddress();

        // 计算价格
        calculateProductAmount();

        // 初始化公司信息
        initCompanyInfo();
    }

    /**
     * 城市选择下拉框选中事件处理函数
     */
    function handleCitySelect(cityId) {
        var $city = $('#cityId');
        // 初始化服务分类信息
        renderServCategorySelect(function() {
            // 更新产品信息
            initProduct();
        });

        // 更新下拉框选项状态
        updateOptionsStatus($city);

        // 初始化服务区域
        initServiceArea(cityId);
        // 清空地址
        clearAddress();

        // 清空街道信息
        renderStreetIdSelect([]);

        // 初始化预约时间
        initDutyTime(function() {
            // 初始化服务公司信息
            initCompanyInfo();
        });
    }

    /**
     * 城市选择下拉框选中事件处理函数
     */
    function handleCountySelect(countyId, cb) {
        if (countyId) {
            fetchAreaDetailData(countyId).done(function(data) {
                renderStreetIdSelect(data, cb);
            });
        }
    }

    function verifyStreetValidation(params) {
        params.type = getters.getOrderType();
        params.add = options.isNew ? 2 : 1;
        return $http.get(STREET_VALIDATION_URL, params).then(function(data) {
            if (data.status !== 2) {
                return $.Deferred().reject('所选地址不在服务范围');
            }
            var $city = $('#cityId option[value="' + data.cityId + '"]:selected');

            if (!$city[0]) {
                return $.Deferred().reject('所选地址与所选城市不匹配');
            }

            return data;
        });
    }

    /**
     *  标准需要查询的城市名称
     * @param cityName 城市名称
     * @returns {String}
     */
    function normalizeCityName(cityName) {
        return cityName.replace('辖县', '').replace('辖区', '');
    }

    /**
     * 获取城市名称
     * @returns {String} 城市名称
     */
    function getSelectedCityName() {
        return normalizeCityName($('#cityId option:selected').text());
    }
    /**
     * 分点城市切换主城市
     * @returns {String} 城市名称
     */

    function switchCity(cityId) {
        var $cityId = $('#cityId');
        $cityId.val(cityId);
        form.render('select');

        updateOptionsStatus($cityId);
    }



    /**
     * 更新 区域列表
     * @param countyId 区域 Id
     */
    function updateAreaList(countyId) {
        var $areaItems = $("#county-list span");
        $areaItems.removeClass('current');
        if (!countyId) {
            return;
        }

        $areaItems.filter('[data-id="' + countyId + '"]').addClass('current');
    }

    /**
     * 更新区域输入框的值
     * @param countyId 区域 Id
     */
    function updateAreaInput(countyId) {
        $("#countyId").val(countyId);
    }

    /**
     * 更新区域备注值
     * @param countyName 区域名称
     */
    function updateCountyName(countyName) {
        $("#countyName").text(countyName);
    }

    /**
     * 更新区域相关信息
     * @param countyId 区域 Id
     */
    function updateAreaInfo(countyId, countyName) {
        updateAreaList(countyId);
        updateAreaInput(countyId);
        // updateCountyName(countyName);
    }

    /**
     * 更新服务坐标信息
     * @param lnt 经度
     * @param lat 纬度
     */
    function updateLocationInfo(lnt, lat) {
        $('#longitude').val(lnt);
        $('#latitude').val(lat);

        // 初始化行政服务商
        initGridCompany();
    }

    /**
     * 更新街道信息
     * @param {string} value 街道信息
     */
    function updateStreetInfo(value) {
        $('#customerAddress').val(value);
    }

    /**
     * 更新街道信息
     * @param {string} value 街道信息
     */
    function setStreetSource(value) {
        $('#streetSource').val(value);
    }

    function setStreetId(value) {
        $('#communityId').val(value);
    }

    function updateDistrict(value) {
        $('#district').val(value);
    }

    function setUserName(name) {
        $('#username').val(name);
    }

    function setStreetInfo(street) {
        $('#customerAddress').val(street);
    }

    function setAddressInfo(address) {
        $('input[name="address"]').val(address);
    }

    function manualSetFormValue(values) {
        form.val("zmn-order-add-form", values);
    }

    function manualSetSelectValue(selector, value) {
        var $select = $(selector);
        $select.find('option').removeProp('selected').prop('disabled', false).prop('selected', false);
        $select.find('option[value="' + value + '"]').prop('selected', true).prop('disabled', true);
    }

    function setProviceInfo(value) {
        $('input[name="provinceId"]').val(value);
        manualSetSelectValue('#provinceId', value);
        manualSetFormValue({ provinceId: value });
    }

    function setCityInfo(value) {
        $('input[name="cityId"]').val(value);
        manualSetSelectValue('#cityId', value);
        manualSetFormValue({ cityId: value });
    }

    function setGender(sex) {
        var $checkboxList = $('input[name="gender"]');

        $checkboxList.filter('checked').attr('checked', false);

        $checkboxList.filter('[value="' + sex + '"]').attr('checked', true);
    }

    /**
     * 检查服务是否可用
     */
    function checkServiceValidation(data) {
        var lng = $('#longitude').val();
        var lat = $('#latitude').val();
        var district = $('#district').val();

        var channelId = getters.getChannelId();
        var cityId = $('#cityId option:selected').val();
        var servCategId = getters.getServCategId();
        var productShowType = getters.getProductShowType();
        var productId = getters.getProductId();
        var countyId = getters.getCountyId();
        if (!channelId) {
            layer.msg('请先选择渠道');
            return;
        } else if (!cityId) {
            layer.msg('请先选择城市');
            return;
        } else if (!servCategId) {
            layer.msg('请先选择服务类型');
            return;
        } else if (!productId) {
            layer.msg('请先选择产品');
            return;
        }

        // 验证所选地址是否在服务范围
        verifyStreetValidation({
            bizType: getters.getBizType(),
            productId: productId,
            channelId: channelId,
            cityId: cityId,
            longitude: lng,
            latitude: lat,
            servCategId: servCategId,
            productShowType: productShowType,
            areaName: district,
            countyId: countyId
        }).then(function(data) {
            if (cityId != data.cityId) {
                switchCity(data.cityId);
            }

            updateAreaInfo(data.countyId);
            updateLocationInfo(lng, lat);

            // 初始化公司信息
            initCompanyInfo();

        }, function(msg) {
            layer.msg(msg);
            clearAddress();
            updateAreaInfo('', '');
        });
    }

    /**
     * 检查服务信息完成性
     */
    function checkServiceInfoCompleteness() {
        var lng = $('#longitude').val();
        var lat = $('#latitude').val();
        var customerAddress = $('#customerAddress').val();

        var channelId = getters.getChannelId();
        var cityId = $('#cityId option:selected').val();
        var servCategId = getters.getServCategId();
        var productId = getters.getProductId();
        return lng && lat && customerAddress && channelId && cityId && servCategId && productId;
    }

    /**
     * 检查百度地图插件是否可用
     * @returns {{msg: string, status: boolean}}
     */
    function checkMapAvailability() {
        var result = {
            status: true,
            msg: ''
        };

        var channelId = getters.getChannelId();
        var cityId = $('#cityId option:selected').val();
        var productId = getters.getProductId();

        if (!channelId) {
            result = {
                status: false,
                msg: '请先选择渠道'
            };
        } else if (!cityId) {
            result = {
                status: false,
                msg: '请先选择城市'
            };
        }

        return result;
    }

    // 检查城市
    function checkChannelIdAndCityId(channelId, cityId) {
        if (!channelId || !cityId) return;

        var params = {
            channelId: channelId,
            cityId: cityId,
            showType: getters.getProductShowType()
        }

        $http.get(CHECK_CHANNELID_CITYID_URL, params).then(function(data) {

        }, function(msg) {
            zmnUtils.layui.toastError(msg);
            initCitySelect(getters.getProvinceId(), channelId, false);
            if (msg.indexOf('未开通') > 0) {
                clearAddress();
            }
        });
    }

    /**
     * 检查是否平台直派
     * @param plat
     * @param cityId
     * @param bizType
     */
    function checkGrid(cityId, callBack) {
        // 返修单不显示校验服务商
        if (!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
            return;
        }
        $http.$get(IS_GRID, {
            platWork: getters.getPlatWork(),
            cityId: cityId,
            bizType: getters.getBizType()
        }).then(function(data) {
            if (data == 20) {
                isGrid = false;
                $("#preCompany").text('校验服务商');
                $("#gridCompany").html("");
            } else {
                $("#preCompany").text('');
                isGrid = true;
                $("#company").html("");
            }

            if (callBack) {
                callBack(isGrid);
            }
        }, function(msg) {
            layer.msg('网络错误');
        });
    }

    /**
     * 获取自动派单时间
     * @param plat
     * @param cityId
     * @param bizType
     */
    function getAutoDistributeTime() {
        if (!getters.getCityId()) {
            $("#auto-distribute-time").text('');
            return;
        }
        $http
            .$get(GET_AUTO_DISTRIBUTE_TIME, {
                platWork: getters.getPlatWork(),
                cityId: getters.getCityId(),
                bizType: getters.getBizType(),
            })
            .then(
                function(data) {
                    if (data) {
                        $("#auto-distribute-time").text('当前城市的自动派单时间：' + data);
                    } else {
                        $("#auto-distribute-time").text('');
                    }
                },
                function(msg) {}
            );
    }
    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('paste', '#telephone, #telephone2, #telephone3', function(e) {
            if (this.disabled) {
                return;
            }
            // 粘贴处理
            let $telephone = $(this);
            let pastedData = e.originalEvent.clipboardData.getData('text');
            if (pastedData && pastedData.match(/\{\s*\"show\"\s*\:\s*\"(?<show>.+)\"\s*\,\s*\"ciphertext\"\s*\:\s*\"(?<ciphertext>.+)\"\s*\}/)) {
                let data = JSON.parse(pastedData);
                $telephone.val(data.show);
                $telephone.data('val', data.show);
                $telephone.data('crypto-phone', data.ciphertext);

                // 解密处理
                $http.get(GET_DECRYPT_PHONE_URL, {
                    cryptoPhone: data.ciphertext
                }).then(
                    function(data) {
                        $telephone.data('real-val', data.realPhone);
                        $telephone.trigger('change');
                    },
                    function(msg) {
                        $telephone.val('');
                        $telephone.data('val', '');
                        $telephone.data('real-val', '');
                        $telephone.data('crypto-phone', '');
                        $telephone.trigger('change');
                    }
                );
            } else {
                $telephone.val(pastedData.replace(/\s+/g,""));
                $telephone.data('val', '');
                $telephone.data('real-val', '');
                $telephone.data('crypto-phone', '');
                $telephone.trigger('change');
            }
            return false;
        });

        // 电话号码输入框输入事件
        $('#btn-discount').on('click', function() {
            $('#show-discount-div').html('')
                // 渠道id
            if ($('#show-discount-div')[0].className == 'hidden') {
                $('#show-discount-div')[0].className = 'show'
            } else {
                $('#show-discount-div')[0].className = 'hidden'
            }
            if (!getters.getChannelId()) {
                return;
            }

            // 城市id
            if (!getters.getCityId()) {
                return;
            }

            // 产品id
            if (!getters.getProductId()) {
                return;
            }

            var price = $("#amount").data("price");
            if (!price) {
                price = null;
            }
            // 批次集合
            let batchListJson = "";
            if (discountTelephoneMap.get(getters.getTelephone())) {
                let batchList = Array.from(discountTelephoneMap.get(getters.getTelephone()).values()).map((batch) => JSON.stringify(batch));
                batchListJson = "[" + batchList.join(",") + "]";
            }
            $http
                .$get(GET_SHOW_DISCOUNT_URL, {
                    plat: getters.getPlat(),
                    platWork: getters.getPlatWork(),
                    channelId: getters.getChannelId(),
                    cityId: getters.getCityId(),
                    productId: getters.getProductId(),
                    showType: getters.getProductShowType(),
                    bizType: getters.getBizType(),
                    type: getters.getType(),
                    servItemType: $("#servItemType").val(),
                    price: price,
                    telephone: getters.getTelephone(),
                    brandId: getters.getBrandId(),
                    productNum: getters.getCount(),
                    batchListJson: batchListJson,
                })
                .then(
                    function(data) {
                        // 标记当前操作的产品位置
                        let url = SYS_BASE_URL_ENUM.dms + data;
                        var dom = '<iframe scrolling="auto" allowtransparency="true" frameborder="0" src="' + url + '" style="height: 382px;width: 100%;"></iframe>'
                        $('#show-discount-div').html(dom);
                    },
                    function(msg) {
                        layer.msg(msg);
                    }
                );

        });

        // 电话号码输入框输入事件
        $('#telephone, #telephone2, #telephone3').on('input', function() {
            var $this = $(this);
            $this.val($this.val().replace(/[^\d\*]/ig, ''));
        });

        // 渠道单号输入框输入事件
        $('#outerId').on('input', function() {
            var channelId = getters.getChannelId();

            var $this = $(this);
            var data = $this.val();
            var length = 32;
            // 不同渠道 不同处理  32852  32850  42023  1352  41889
            if (channelId === '32852') {
                // 例:220525-521498838500485  长度：22
                length = 22;
                data = data.replace(/[^A-Za-z0-9-]/g, '');
            } else if (channelId === '32850' || channelId === '42023') {
                // 例:220525-1597575397080261783  长度：19
                data = data.replace(/[^A-Za-z0-9]/g, '');
                length = 19;
            } else if (channelId === '1352' || channelId === '41889') {
                // 例:25053144241  长度：19
                data = data.replace(/[^A-Za-z0-9]/g, '');
                length = 12;
            } else {
                data = data.replace(/[^A-Za-z0-9]/g, '');
            }

            if (!data) {
                $this.val(data);
            } else {
                $this.val(data.substr(0, length));
            }
        });

        //自定义验证规则
        form.verify({
            radio: function(value, item) {
                var $ = layui.$;
                var verifyName = $(item).attr('name'),
                    verifyType = $(item).attr('type'),
                    formElem = $(item).parents('.layui-form') //获取当前所在的form元素，如果存在的话
                    ,
                    verifyElem = formElem.find('input[name=' + verifyName + ']') //获取需要校验的元素
                    ,
                    isTrue = verifyElem.is(':checked') //是否命中校验
                    ,
                    focusElem = verifyElem.next().find('i.layui-icon'); //焦点元素
                if (!isTrue || !value) {
                    //定位焦点
                    focusElem.css(verifyType == 'radio' ? { "color": "#ff5722" } : { "border-color": "#ff5722" });
                    //对非输入框设置焦点
                    focusElem.first().attr("tabIndex", "1").css("outline", "0").blur(function() {
                        focusElem.css(verifyType == 'radio' ? { "color": "" } : { "border-color": "" });
                    }).focus();
                    return '必填项不能为空';
                }
            },
            brand: function(value, item) {
                // 品牌验证， 家电安装、家电清洗、家电维修 必选，其它不必须
                var servCategId = getters.getServCategId();
                if ((servCategId == '1001' || servCategId == '1002' || servCategId == '1003') && !value) {
                    return '必填项不能为空';
                }
            }
        });

        // 服务类型选择下拉框的点击事件处理器
        form.on('select(servCategory)', function(data) {
            var servCategId = data.value;

            // 更新下拉框选项状态
            updateOptionsStatus(data.elem);

            // 初始化产品下拉框
            initProduct(0, 1);

            // 初始化产品数量输入框
            initCountInput(1);

            initProductUnit('');

            // 初始化品牌下拉框
            initBrandSelect('');

            // 初始化常见故障
            initCommonFaultsCheckboxGroup('');

            // 如果前面的信息完整就检查服务服务可用性
            if (checkServiceInfoCompleteness()) {
                checkServiceValidation();
            }

            // 初始化公司信息
            // initCompanyInfo();

            // 清理预约信息
            clearDutyTime();

            // 检查报价相关信息
            checkAdvanceQuote();
        });

        // 订单类型单选框的选中事件处理器
        form.on('radio(product-showtype)', function(data) {
            var value = data.value;

            // 初始化服务分类
            renderServCategorySelect(function() {
                // 初始化产品下拉框
                initProduct(1);

                // 初始化产品数量输入框
                initCountInput(1, value);

                initProductUnit('');

                // 初始化品牌下拉框
                //initBrandSelect(getters.getBrand());

                // 初始化常见故障
                initCommonFaultsCheckboxGroup('');

                form.render();
            });

            // 如果前面的信息完整就检查服务服务可用性
            if (checkServiceInfoCompleteness()) {
                checkServiceValidation();
            }

            // 初始化公司信息
            // initCompanyInfo();

            form.render();
        });

        // 服务品类选择下拉框的点击事件处理器
        form.on('select(product)', function(data) {
            var productId = data.value;

            var serviceGategoryId = $(data.elem).find('option[value="' + productId + '"]').data('pid');

            if (serviceGategoryId) {
                $('#servCategoryId').val(serviceGategoryId);
                form.render('select');
            }

            var unit = $(data.elem).find('option:selected').data('unit') || '';

            // 初始化产品数量输入框
            initCountInput(1);

            // 初始化产品单位
            initProductUnit(unit);
            // 初始化常见故障多选框组
            initCommonFaultsCheckboxGroup(productId);

            // 计算价格
            calculateProductAmount();

            // 如果前面的信息完整就检查服务服务可用性
            if (checkServiceInfoCompleteness()) {
                checkServiceValidation();
            }

            // 初始化预约时间
            initDutyTime();

            EventBus.$emit('productSelect', data);

            // 校验取消重复
            checkDuplicateOrder();

            // 检查报价相关信息
            checkAdvanceQuote();
        });

        // 服务品类选择下拉框的点击事件处理器
        form.on('select(showProduct)', function(data) {
            var productId = data.value;

            var serviceGategoryId = $(data.elem).find('option[value="' + productId + '"]').data('pid');

            if (serviceGategoryId) {
                $('#servCategoryId').val(serviceGategoryId);
                form.render('select');
            }

            var unit = $(data.elem).find('option:selected').data('unit') || '';

            // 初始化产品数量输入框
            initCountInput(1);

            // 初始化产品单位
            initProductUnit(unit);
            // 初始化常见故障多选框组
            initCommonFaultsCheckboxGroup(productId);

            // 计算价格
            calculateProductAmount();
            // 重新计算预约时间
            // orderSche.reProcessDutyTime();

            // 初始化预约时间
            initDutyTime(function() {
                // 初始化服务公司信息
                initCompanyInfo();
            });

            // 初始化网格信息
            initGridCompany();

            // 校验取消重复
            checkDuplicateOrder();

            // 检查报价相关信息
            checkAdvanceQuote();
        });

        // 产品数量输入框的 input 事件、change 事件
        $('#count').on('input', function() {
            var $this = $(this);
            $this.val($this.val().replace(/[^\d]/ig, ''));
        }).on('change', function() {
            // 计算价格
            calculateProductAmount();
        });


        // 省份选择下拉框的点击事件处理器
        form.on('select(province)', function(data) {
            handleProvinceSelect(data.value);
        });

        // 品牌下拉框
        form.on('select(brand)', function(data) {
            calculateProductAmount();

            // 处理提前付逻辑
            setTimeout(function (){
                checkAdvanceQuote()
            }, 500);
        });

        // 城市选择下拉框的点击事件处理器
        form.on('select(city)', function(data) {
            var cityId = data.value;
            var provinceId = $(data.elem).find('option[value="' + cityId + '"]').data('pid');

            if (provinceId) {
                $('#provinceId').val(provinceId);
                form.render('select');
            }

            // 清空预发券相关信息，避免数据错误
            clearAllProductDiscountInfo(null, cityId, null);

            handleCitySelect(cityId);

            //是否平台直派
            checkGrid(cityId);
            // 设置自动派单时间
            // getAutoDistributeTime();

            setTimeout(function (){
                // 检查报价相关信息
                checkAdvanceQuote();
            }, 300);
        });

        // 区县选择下拉框的点击事件处理器
        form.on('select(countyId)', function(data) {
            var countyId = data.value;

            handleCountySelect(countyId);
        });

        // 街道选择下拉框的点击事件处理器
        form.on('select(streetId)', function(data) {
            recreatFuzzyInfo();

            // 初始化预约时间
            initDutyTime(function() {
                // 初始化服务公司信息
                initCompanyInfo();
            });

            // 初始化行政服务商
            initGridCompany();
        });

        // 精确地址与模糊地址切换
        $("#address-type-exact").on('click', function(e) {
            initFuzzyAddress();
        });

        $("#address-type-fuzzy").on('click', function(e) {
            initExactAddress();
        });

        // 街道输入框输入事件
        (function initStreeInputEvent() {
            var timer = null;
            $('#customerAddress').on('input', function(e) {
                e.preventDefault();
                var $this = $(this);

                clearTimeout(timer);
                timer = setTimeout(function() {
                    var queryStr = $this.val();
                    var cityName = getSelectedCityName();
                    var cityId = getters.getCityId();
                    renderStreetSelect({
                        queryStr: queryStr,
                        cityName: cityName,
                        cityId: cityId,
                        ak: addOrderWebAk
                    });
                }, 300);
            });
        })();

        // 街道输入框获取焦点事件
        $('#customerAddress').on('focus', function(e) {
            e.preventDefault();
            var $this = $(this);

            var result = checkMapAvailability();
            if (!result.status) {
                layer.msg(result.msg);
                $this.blur();
            }
        });


        $('#suggestPanel').on('click', 'li:not(.tip)', function(e) {
            e.preventDefault();
            var $li = $(this);
            // 关闭遮罩层
            layer.closeAll();

            var lng = $li.data('lng');
            var lat = $li.data('lat');
            var name = $li.data('name');
            var district = $li.data('district');
            var streetSource = $li.data('source');
            var streetId = $li.data('communityid');

            updateLocationInfo(lng, lat);
            updateStreetInfo(name);
            updateDistrict(district);
            setStreetSource(streetSource);
            setStreetId(streetId);

            // 更新区域list
            setCountyInfo(district, lng, lat, function() {
                // 如果前面的信息完整就检查服务服务可用性
                if (checkServiceInfoCompleteness()) {
                    checkServiceValidation({
                        street: name,
                        longitude: lng,
                        latitude: lat
                    });
                }
            });

            checkEpidemicControl();

            // 初始化预约时间
            initDutyTime();
            $('#suggestPanel').hide();
        });

        // 百度地图按钮点击事件
        $('#btn-map').on('click', function(e) {
            e.preventDefault();

            var result = checkMapAvailability();

            if (!result.status) {
                layer.msg(result.msg);
                return;
            }
            // 处理逻辑
            var cityId = getters.getCityId();
            var servCategId = getters.getServCategId();
            var productShowType = getters.getProductShowType();
            var productId = getters.getProductId();
            var bizType = getters.getBizType();

            parent.addressOptions = {
                location: getters.getLocation(),
                cityId: cityId,
                servCategId: servCategId,
                productShowType: productShowType,
                productId: productId,
                cityName: getters.getCityName(),
                street: getters.getStreet(),
                streetId: getters.getStreetId(),
                streetSource: getters.getStreetSource(),
                countyId: getters.getCountyId(),
                countyName: getters.getInputCountyName(),
                plat: getters.getPlatWork(),
                verifyFunc: function(selectedAddress, succ_cb, fail_cb) {
                    setCountyInfo(selectedAddress.addressComponents.district, selectedAddress.point.lng, selectedAddress.point.lat, function(countyId) {
                        verifyStreetValidation({
                            bizType: bizType,
                            cityId: cityId,
                            servCategId: servCategId,
                            productShowType: productShowType,
                            productId: productId,
                            longitude: selectedAddress.point.lng,
                            latitude: selectedAddress.point.lat,
                            countyId: countyId,
                        }).then(
                            function(data) {
                                if (cityId != data.cityId) {
                                    switchCity(data.cityId);
                                }
                                succ_cb(data);
                            },
                            function(msg) {
                                fail_cb(msg);
                            }
                        );
                    })
                },
                callBack: function(data, addressObj) {
                    updateAreaInfo(data.countyId);
                    updateStreetInfo(addressObj.address);
                    updateLocationInfo(addressObj.point.lng, addressObj.point.lat);
                    setStreetId(addressObj.communityId);
                    setStreetSource(addressObj.streetSource);

                    // 初始化公司信息
                    initCompanyInfo();

                    // 初始化预约时间
                    initDutyTime();

                    // 疫情管控
                    checkEpidemicControl();
                }
            };

            parent.layer.open({
                title: "选择地址",
                type: 2,
                area: ['90%', '90vh'],
                fix: true, //不固定
                maxmin: false,
                content: OMS_BASE_URL + '/order/addressmap.ation',
                end: function() {
                    $("#customerAddress").focus();
                }
            });
        });

        // 产品相关输入框的 focus 事件
        $('#product-list').on('focus', 'input', function() {
            if (!$('#cityId option:checked').val()) {
                layer.msg('请先选择城市');
                $(this).blur();
            }
        });

        // 查看价格表按钮的点击事件
        $('#btn-price-table,#btn-price-fault,#btn-price-advance-pay,#amount-quotation-three').on('click', function(e) {
            e.preventDefault();

            var cityId = getters.getCityId();
            var productId = getters.getProductId();
            var channelId = getters.getChannelId();
            var bizType = getters.getBizType();
            var type = getters.getType();
            var plat = getters.getPlatWork();
            var brandId = getters.getBrandId();
            var productShowType = getters.getProductShowType();
            var orderId = options.isUpdate ? getters.getOrderId() : null;
            var workId = options.isUpdate ? getters.getWorkId() : null;

            if (!channelId) {
                layer.msg('请先选择渠道');
                return;
            }

            if (!cityId) {
                layer.msg('请先选择城市');
                return;
            }

            if (!productId) {
                layer.msg('请先选择产品');
                return;
            }

            if (!brandId) {
                layer.msg('请先选择品牌');
                return;
            }

            var priceTableURL = zmnUtils.serializeURL(PRODUCT_PRICE_TABLE_URL, {
                cityId: cityId,
                productId: productId,
                channelId: channelId,
                bizType: bizType || 1, // 默认保外
                type: type,
                plat: plat,
                brandId: brandId,
                tariffType: productShowType,
                orderId: orderId,
                workId: workId
            });

            layer.open({
                type: 2,
                title: '价格表',
                content: priceTableURL,
                shade: [0.8, '#393D49'],
                area: ['98%', '96vh']
            });
        });


        // 选择预约时间按钮的点击事件
        $('#btn-duty-time').on('click', function(e) {
            e.preventDefault();

            var layer = parent.layui.layer;

            //下单地址录入校验
            if (!getters.getCityId()) {
                layer.alert("请选择城市", { offset: "250px" });
                return;
            }
            if (!getters.getLatitude() || !getters.getLongitude()) {
                layer.alert("请先填写下单地址", { offset: "250px" });
                return;
            }

            // 检查品类和数量
            if (!getters.getProductId()) {
                layer.alert("请选择产品", { offset: "250px" });
                return;
            }


            var productId = getLayuiSelectValue("#product");
            var showProductId = getLayuiSelectValue("#showProduct")

            layer.open({
                title: "选择预约时间",
                type: 2,
                shift: 7,
                area: ['980px', '650px'],
                fix: true,
                offset: ['6px'],
                zIndex: 99999999999,
                content: OMS_BASE_URL + '/order/dutytime',
                success: function(layero, index) {
                    parent.layer.setTop(layero);
                    parent.window.dutyTimeOptions = {
                        dutyTime: getters.getDutyTime(),
                        plat: getters.getPlat(),
                        platWork: getters.getPlatWork(),
                        channelId: getters.getChannelId(),
                        cityId: getters.getCityId(),
                        productId: productId,
                        showProductId: showProductId,
                        workId: getters.getWorkId(),
                        type: getters.getOrderType(),
                        productNum: getters.getCount(),
                        latitude: getters.getLatitude(),
                        longitude: getters.getLongitude(),
                        isGrid: isGrid,
                        servCategId: getters.getServCategId(),
                        bizType: getters.getBizType(),
                        isAvailableWeek: isAvailableWeek,
                        changeDutyData: changeDutyData,
                        confirm: function(time, changeData) {
                            initDutyTimeInfo(time, time);
                            // 更新服务商信息
                            initCompanyInfo();
                            if (changeData.startIndex) {
                                changeDutyData = changeData;
                                if (changeData.workId) {
                                    $("#exchangeWorkId").val(changeData.workId);
                                } else {
                                    $("#exchangeWorkId").val('');
                                }
                            }
                        }
                    };
                }
            });
        });

        // 预约时间多选框勾选事件
        form.on('checkbox(duty-time-checkbox)', function(data) {
            dutyStatusCheck(data.elem.checked);
        });

        // 监听意向单添加按钮事件
        form.on('submit(purpose)', function(data) {
            savePurpose(data.field, data.elem).then(function() {
                layer.closeAll();

                zmnUtils.layui.toastSuccess('操作成功', function() {
                    location.reload();
                });
            });

            return false;
        });

        // 保存确认按钮点击事件
        form.on('submit(confirmbtn)', function(data) {
            // 平台直派模式，子公司员工修改时，如果行政子公司发生变更不允许修改
            let isCheck = isGrid && branchCompany && gridCompanyId && orderGridCompanyId != gridCompanyId;
            if (isCheck) {
                layer.msg("修改后，订单不在您的服务范围内，请反馈至总部派单修改");
                return false;
            }

            // 保存
            var params = formUtils.normalize(data);
            if (!params) {
                return false;
            }
            // 复制工单，需要将platWork->plat
            if (params.isCopy) {
                params.plat = getters.getPlatWork();
            }
            console.log(params)

            if (orderPostTable && table.cache['orderPostTable']) {
                params.orderPostList = table.cache['orderPostTable'];
            }

            if (params.telephone && params.telephone.indexOf('*') > 0) {
                params.telephone = $('#telephone').data('real-val');
                delete params.realTelephone;
            }
            if (params.telephone2 && params.telephone2.indexOf('*') > 0) {
                params.telephone2 = $('#telephone2').data('real-val');
                delete params.realTelephone2;
            }
            if (params.telephone3 && params.telephone3.indexOf('*') > 0) {
                params.telephone3 = $('#telephone3').data('real-val');
                delete params.realTelephone3;
            }

            let callback = function() {
                // 提交之前的校验 无论工单类型
                if (!verifyBeforeSubmit()) {
                    return false;
                }

                saveOrderInfo(params, data.elem).then(function(data) {
                    layer.msg('操作成功', { icon: 1, time: 1000 }, function() {
                        zmnUtils.isFunction(options.success) ?
                            options.success(data) :
                            (
                                options.modifyDetail ?
                                goWorkModifyDetail(data.orderWork.orderId, data.orderWork.workId) :
                                goWorkDetail(data.orderWork.orderId, data.orderWork.workId)
                            );
                    });
                }, function(msg) {
                    layer.msg(msg);
                });
            }

            verifyChangeAddressOrDutyTimeOrProduct(function(params) {
                clearTimeout(debounceTimer);
                debounceTimer = setTimeout(callback, 200);
            }, params);

            return false;
        });

        form.on('select(channelId)', function(data) {
            var channelId = data.value;
            // 更新plat
            var channelPlat = $(data.elem).find("option:selected").attr("plat");
            if (channelPlat) {
                $("#plat").val(channelPlat);
            }

            // 清空预发券相关信息，避免数据错误
            clearAllProductDiscountInfo(channelId, null, null);


            // 加载渠道开通的城市，选择渠道时提示
            initCitySelect(getters.getProvinceId(), data.value, true, function() {
                // 初始化服务分类信息
                renderServCategorySelect(function() {
                    // 更新产品信息
                    initProduct();

                    calculateProductAmount();
                });
            });
            // 校验当前渠道是否开通选中的城市
            // checkChannelIdAndCityId(data.value, getters.getCityId(), '当前渠道未开通：'+ getLayuiSelectText('#cityId') +'，请重新选择城市');
            //下单渠道是否 选择外部店铺
            checkSelectExternalShop(channelId);
        });

        // 校验服务商的点击事件
        $('#preCompany').on('click', function(e) {
            e.preventDefault();

            var layer = parent.layui.layer;

            // 检查产品
            if (!getters.getProductId()) {
                layer.alert("请选择产品", { offset: "250px" });
                return;
            }

            // 检查城市
            if (!getters.getCityId()) {
                layer.alert("请选择城市", { offset: "250px" });
                return;
            }

            // 检查经纬度
            if (!getters.getLongitude()) {
                layer.alert("请选择经纬度", { offset: "250px" });
                return;
            }

            let plat = getters.getPlatWork();

            let url = OMS_BASE_URL + '/order/check/company.action';
            if ($(document).attr("title") != "快捷下单") {
                url += '?plat=' + plat;
            }

            layer.open({
                title: "校验服务商",
                type: 2,
                shift: 7,
                area: ['780px', '345px'],
                fix: true,
                zIndex: 99999999999,
                content: url,
                success: function(layero, index) {
                    parent.layer.setTop(layero);
                    parent.window.checkCompanyOptions = {
                        workId: getters.getWorkId(),
                        reworkId: $("#reworkId").val(),
                        type: getters.getOrderType(),
                        recommenderId: $("#recommenderId").val(),
                        channelId: getters.getChannelId(),
                        platWork: getters.getPlatWork(),
                        plat: getters.getPlat(),
                        bizType: getters.getBizType(),
                        cityId: getters.getCityId(),
                        productId: getters.getProductId(),
                        longitude: getters.getLongitude(),
                        latitude: getters.getLatitude(),
                        streetId: getters.getStreetId(),
                        countyId: getters.getCountyId(),
                        dutyTime: getters.getDutyTime()
                    };
                }
            });
        });

        // 各文本框粘贴事件文本处理
        $('body').on('change', 'input[name="userName"], input[name="address"], #expressCode',
            function (e) {
                if (this.disabled) {
                    return;
                }
                var $this = $(this);
                $this.val($this.val().replace(/\s+/g,""));
            });

        // 初始化报价事件
        initAdvanceQuoteEvent();

        // 报价/话务挽留短信短信初始化
        initCustomerMessageEvent();

    }

    /**
     * 报价/话务挽留短信短信初始化
     */
    function initCustomerMessageEvent(){
        // 话务挽留短信 - 后台录单 - 话务挽留短信
        $('#sendOrderTransferFailMessageBtn').on('click', function (){
            let telephone = getters.getTelephone();
            if (!telephone) {
                layer.msg('用户电话不能为空！');
                return false;
            }
            let productId = getters.getProductId();
            if (!productId) {
                layer.msg('产品不能为空！');
                return false;
            }

            let hideTel = String(telephone).replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
            layer.open({
                title:'发送挽留短信',
                content: '确定向用户'+hideTel+'发送挽留短信吗？<br>用户可通过短信访问微信小程序对应的商品详情页，查看商品详情',
                btn: ['确认', '取消'],
                yes: function(index, layero) {
                    $http.get(GET_ORDER_TRANSFER_FAIL_URL, {
                        telphone: telephone,
                        productId: productId,
                    }).then(function () {
                        layer.msg('发送成功');
                    });
                },
                cancel: function() {
                },
            });
            return false;
        });

        // 修改订单 - 话务确认报价失败
        $('#sendOrderConfirmQuotedFailMessageBtn').on('click', function (){
            let telephone = getters.getTelephone();
            if (!telephone) {
                layer.msg('用户电话不能为空！');
                return false;
            }
            let productId = getters.getProductId();
            if (!productId) {
                layer.msg('产品不能为空！');
                return false;
            }

            let hideTel = String(telephone).replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
            layer.open({
                title:'发送确认报价短信',
                content: '确定向用户'+hideTel+'用户发送确认报价短信吗？<br>用户可通过商品详情页了解报价或联系客服确认报价',
                btn: ['确认', '取消'],
                yes: function(index, layero) {
                    $http.get(GET_ORDER_CONFIRM_QUOTED_FAIL_URL, {
                        orderId: getters.getOrderId(),
                        workId: getters.getWorkId(),
                        telphone: telephone,
                        productId: productId,
                        dutyTime: getters.getDutyTime(),
                    }).then(function () {
                        layer.msg('发送短信成功');
                    });
                },
                cancel: function() {
                },
            });

            return false;
        })
    }

    var verifyRules = {
        // 用户电话验证
        tel: function(value, el) {
            value = $.trim(value);

            if (value === '') {
                return;
            }

            let hideTelephone = $(el).data('val');
            if (hideTelephone && value == hideTelephone) {
                return;
            }
            if (validate.phone(value) || validate.tel(value)) {
                return;
            }

            return '请正确填写您的电话号码';
        },
        mobile: function(value, el) {
            value = $.trim(value);

            if (value === '') {
                return;
            }

            let hideTelephone = $(el).data('val');
            if (hideTelephone && value == hideTelephone) {
                return;
            }

            if (validate.phone(value)) {
                return;
            }

            return '请正确填写您的手机号码';
        },
        // 产品数量
        count: function(value) {
            value = $.trim(value);
            var minValue = 1;
            var maxValue = 10;

            if (getters.getProductShowType() === PRODUCT_SHOW_TYPE_ENUM.FRONT) {
                maxValue = maxProductCount;
            }

            if (!validate.isPosInt(value)) {
                return '请正确填写产品数量';
            } else if (value > maxValue) {
                return '产品数量的最大值为 ' + maxValue;
            } else {
                return;
            }
        },
        // 检查原单号
        checkReworkId: function(value) {
            if (getters.getOrderType() === '1') {
                return;
            }

            if (!$.trim(value)) {
                return '必填项不能为空';
            }

            var telephone = getters.getTelephone();
            var productId = getters.getProductId();
            var longitude = getters.getLocation().lng;
            var latitude = getters.getLocation().lat;

            if (!telephone ||
                !productId ||
                !longitude ||
                !latitude) {
                return;
            }

            var flag = false;
            var failMessage;

            checkReworkId(value).then(function() {
                flag = true;
            }, function(msg) {
                failMessage = msg || '网络错误，请重试';
            });

            if (!flag) {
                return failMessage;
            }

            return;
        },

        // 验证预约时间
        dutyTime: function(value) {
            if (!$("#duty-time-checkbox").is(':checked') && !value) {
                if (getters.getPlatWork() == '1' || getters.getPlatWork() == "3") {
                    return; // 言而有信，一步维修不需要预约时间校验
                }
                return '请选择预约时间!';
            }
            return;
        },

        // 验证长度
        maxLengthFactory: function(length) {
            return function(value) {
                if (value.length > length) {
                    return '输入字符超过最大长度，最大长度为：' + length;
                } else {
                    return;
                }
            };
        },
        // 渠道单号
        outerId : function(value) {
            let channelId = getters.getChannelId();

            // 不同渠道 不同处理
            if (channelId === '32852') {
                // 例:220525-521498838500485  长度：22
                if (value.length != 22) {
                    return "渠道单号必填且长度只能为22位";
                }
                return;
            }

            if (channelId === '32850' || channelId === '42023') {
                // 例:220525-1597575397080261783  长度：19
                if (value.length != 19) {
                    return "渠道单号必填且长度只能为19位";
                }
                return;
            }

            if (channelId === '1352' || channelId === '41889') {
                // 例:25053144241  长度：19
                if (value.length != 12) {
                    return "渠道单号必填且长度只能为12位";
                }
                return;
            }
        },

        // 新建返修单时：返修原因必选验证
        reworkReason: function (value, el) {
            if (checkEleShow("#rework-reason") && $("input[name=reworkReasonList]:checked").length == 0) {
                return '请选择至少一个返修原因';
            }
        },
    }

    function dutyStatusCheck(checked) {
        if (checked) {
            $('#duty-time-wrapper').hide();
            $('#duty-fail-code').removeClass('layui-hide');
            $('#next-contact-time').removeClass('layui-hide');

            $('#dutyFailCode').attr('lay-verify', 'required');
            $('#next-contact-date-input').attr('lay-verify', 'required');
            $('#next-contact-time-input').attr('lay-verify', 'required');
            $('#duty-time-input').attr('lay-verify', '');

            initDutyTimeInfo('', '');
            // 更新服务商信息
            initCompanyInfo();
        } else {
            $('#duty-time-wrapper').show();
            $('#duty-fail-code').addClass('layui-hide');
            $('#next-contact-time').addClass('layui-hide');

            $('#dutyFailCode').attr('lay-verify', '');
            $('#next-contact-date-input').attr('lay-verify', '');
            $('#next-contact-time-input').attr('lay-verify', '');
        }
    }

    function initVerifyRules() {
        form.verify({
            tel: verifyRules.tel,
            mobile: verifyRules.mobile,
            count: verifyRules.count,
            rework: verifyRules.checkReworkId,
            dutyTime: verifyRules.dutyTime,
            outerId: verifyRules.outerId,
            maxLenTo500: verifyRules.maxLengthFactory(500),
            maxLenTo300: verifyRules.maxLengthFactory(300),
            reworkReason: verifyRules.reworkReason
        });
    }

    /**
     * 清空输入框的值
     */
    function clearInputValue(selector) {
        $(selector).val('');
    }

    /**
     * 清空输入框的值
     */
    function clearSelectValue(selector) {
        var selectedOption = selector + " option:selected";
        $(selectedOption).prop("selected", false);
    }

    /**
     * 显示模糊地址选择框
     */
    function initFuzzyAddress() {
        var $this = $("#address-type-exact");
        $this.addClass('layui-hide');
        $("#exact-address").addClass('layui-hide');
        $("#address-type-fuzzy").removeClass('layui-hide');
        $("#fuzzy-address").removeClass('layui-hide');
        clearAddress();

        $('#customerAddress').attr('lay-verify', '');
        $('#countyId').attr('lay-verify', 'required');
        $('#streetId').attr('lay-verify', 'required');

        // 疫情相关参数清空
        cleanEpidemicControl();
    }

    /**
     * 显示精确地址选择框
     */
    function initExactAddress() {
        var $this = $("#address-type-fuzzy");
        $this.addClass('layui-hide');
        $("#fuzzy-address").addClass('layui-hide');
        $("#address-type-exact").removeClass('layui-hide');
        $("#exact-address").removeClass('layui-hide');
        clearAddress();

        $('#customerAddress').attr('lay-verify', 'required');
        $('#countyId').attr('lay-verify', '');
        $('#streetId').attr('lay-verify', '');

        // 疫情相关参数清空
       cleanEpidemicControl();
    }

    /**
     * 初始化精确地址与模糊地址显示
     */
    function initAddressShow(streetId) {
        if (streetId) {
            initFuzzyAddress();
        } else {
            initExactAddress();
        }
    }

    /**
     * 清空地址相关数据
     */
    function clearAddress() {
        var inputArray = [
            '#customerAddress',
            '#longitude',
            '#latitude',
            "#communityId",
            "#streetSource"
        ];

        $.each(inputArray, function(index, selector) {
            clearInputValue(selector);
        });

        var selectArray = [
            '#countyId',
            '#streetId'
        ];

        $.each(selectArray, function(index, selector) {
            clearSelectValue(selector);
        });

        form.render('select');

        setTimeout(function() {
            $('#suggestPanel ul').html('');
            $('#suggestPanel').hide();
        }, 300);

        initCompanyInfo();

        clearDutyTime();
        // 疫情相关参数清空
        cleanEpidemicControl();
    }

    function clearDutyTime() {
        initDutyTimeInfo("", "");
        $("#gird-group-distribute-master").text('');
    }

    /**
     * 重新生成模糊地址数据
     */
    function recreatFuzzyInfo() {
        var $street = $("#streetId option:selected");
        if ($street) {
            var lon = $street.data('longitude');
            var lat = $street.data('latitude');
            var id = $street.val();
            if (!id == "") {
                if (!lon || !lat) {
                    $street.prop("selected", false);
                    layer.msg("所选街道无经纬度数据，请到基础数据中心完善配置")
                    return;
                }
                $('#longitude').val(lon);
                $('#latitude').val(lat);
                $('#customerAddress').val($street.text());
                $('#streetSource').val(3);

                // 如果前面的信息完整就检查服务服务可用性
                if (checkServiceInfoCompleteness()) {
                    checkServiceValidation();
                }
                // 校验疫情
                checkEpidemicControl();
            }

        }
    }

    /**
     * 初始化行政服务商
     */
    function initGridCompany() {

        // 返修单不显示行政服务商
        if (!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
            return;
        }

        // 平台直派获取行政服务商
        if (isGrid && getters.getStreet() != '' && getters.getLongitude() && getters.getProductId()) {
            $("#gridCompany").removeClass("layui-hide");
            $("#company").addClass("layui-hide");
            $http.$post(GRID_COMPANY_URL, {
                plat: getters.getPlat(),
                channelId: getters.getChannelId(),
                cityId: getters.getCityId,
                countyId: getters.getCountyId(),
                streetId: getters.getStreetId(),
                streetSource: getters.getStreetSource(),
                type: getters.getType(),
                dutyTime: getters.getDutyTime(),
                workId: getters.getWorkId(),
                bizType: getters.getBizType(),
                servCategId: getters.getServCategId(),
                productShowType: getters.getProductShowType() ,
                productId: getters.getProductId(),
                longitude: getters.getLongitude(),
                latitude: getters.getLatitude(),
                telephone: getters.getTelephone(),
                telephone2: getters.getTelephone2(),
                telephone3: getters.getTelephone3(),
                receiveEntranceId: getters.getReceiveEntranceId(),
                requestId: getters.getRequestId()
            }).then(
                function(data) {
                    if (data.message.indexOf('未找到产品信息') != -1) {
                        $("#gridCompany").html("<span>" + data.message + "</span>");
                        // 55507-无法服务子公司
                        gridCompanyId = 55507;
                        $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                    } else {
                        $("#gridCompany").html("<span>" + data.message + "</span>");
                        gridCompanyId = data.gridCompanyId;
                        $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                    }
                },
                function(e) {
                    $("#gridCompany").html("<span style='color: red'>" + e + "</span>");
                    // 55507-无法服务子公司
                    gridCompanyId = 55507;
                    $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                }
            );
            $("#preManageCompanyId").val('');
            $("#preManageCompanyName").val('');
        } else {
            $("#gridCompany").addClass("layui-hide");
            $("#gridCompany").html("");
            $("#company").removeClass("layui-hide");
        }
    }

    function goWorkDetail(orderId, workId) {
        if (workId != null) {
            window.location.href = objOfURL.workDetail + '?' + zmnUtils.urlEncode({
                orderId: orderId,
                workId: workId
            });
        } else {
            layer.open({
                content: '下单成功！',
                btn: ['确认'],
                yes: function(index, layero) {
                    location.reload();
                    //parent.layui.admin.events.closeThisTabs();
                },
                cancel: function() {
                    //右上角关闭回调
                    location.reload();
                    //parent.layui.admin.events.closeThisTabs();
                }
            });
        }
    }

    function goWorkModifyDetail(orderId, workId) {
        window.location.href = objOfURL.workModifyDetail + '?' + zmnUtils.urlEncode({
            orderId: orderId,
            workId: workId
        });
    }

    /**
     * 初始化下次联系时间选择框
     */
    function renderNextTimeDatePicker() {
        var datePickerElem = '#next-contact-date-input';
        var timePickerElem = '#next-contact-time-input';
        var nowDate = $(datePickerElem).data('date');
        var nextHour = $(timePickerElem).data('hour');
        var minDate = $(datePickerElem).data('today-available') ?
            nowDate :
            dayjs(nowDate).add(1, 'day').format('YYYY-MM-DD');
        var timePickerInstance;

        laydate.render({
            elem: datePickerElem,
            type: 'date',
            format: 'yyyy-MM-dd',
            min: minDate,
            done: function(value) {
                var minHour = nowDate === value ? nextHour : 8;
                if (!timePickerInstance) {
                    timePickerInstance = laydate.render({
                        elem: timePickerElem,
                        type: 'time',
                        format: 'HH:mm:ss',
                        theme: 'time-hour',
                        min: minHour + ':00:00',
                        max: '18:00:00',
                        btns: ['clear', 'confirm']
                    });
                } else {
                    timePickerInstance.config.min.hours = minHour;
                }

                // 切换时间选择框的验证状态
                if (value) {
                    $(timePickerElem).attr('lay-verify', 'required');
                } else {
                    $(timePickerElem).attr('lay-verify', '');
                }
            }
        });
    }

    /**
     * 初始化订单快递
     */
    function renderNewOrderPost() {
        orderPostTable = table.render({
            elem: '#orderPostTable',
            width: 526,
            data: [],
            cols: [
                [
                    { field: 'expressCode', title: '单号', width: '30%', align: "center" },
                    { field: 'expressCompany', title: '快递公司', width: '30%', align: "center" },
                    { field: 'itemTypeName', title: '类型', width: '20%', align: "center" },
                    { title: '操作', align: "center", toolbar: '#btns' }
                ]
            ],
            done: function() {},
            even: true
        })

        table.on('tool(orderPostTable)', function(obj) {
            if (obj.event === 'del') {
                var postData = table.cache["orderPostTable"];
                postData.splice(obj.tr.data('index'), 1) //根据索引删除当前行
                orderPostTable.reload({
                    data: postData
                });
            }
        });

        $("#addOrderPost").on('click', function() {
            var expressCode = $("#expressCode").val();
            var expressCompany = $("#expressCompany").val();
            if (zmnUtil.isEmptyNull(expressCode)) {
                layer.msg("请输入快递单号");
                return
            }
            if (zmnUtil.isEmptyNull(expressCompany)) {
                layer.msg("请选择快递公司");
                return
            }

            var postDataList = table.cache["orderPostTable"];
            postDataList.push({
                expressCode: expressCode,
                expressCompanyCode: expressCompany,
                expressCompany: $("#expressCompany option:selected").text(),
                itemType: 1,
                itemTypeName: '新机'
            });

            orderPostTable.reload({
                data: postDataList
            });
        });
    }

    /**
     * 是否存在店铺下拉
     * @returns {boolean}
     */
    function existShopSelect(){
        return options.enableExternalShop;
    }

    /**
     *  校验疫情
     * @param
     */
    function checkEpidemicControl() {
        let obj = {
            longitude: getters.getLongitude(),
            latitude: getters.getLatitude(),
            countyId: getters.getCountyId()
        }

        if (!obj.longitude || !obj.latitude) {
            $("#spanEpidemicControlTip").text('');
            $("#divEpidemicControlTip").text('');
            return;
        }

        $http.get(CHECK_EPIDEMIC_CONTROL, obj).then(
            function (data) {
                if (data === 1) {
                    $("#spanEpidemicControlTip").text('');
                    $("#divEpidemicControlTip")
                        .addClass("epidemicOfOpen")
                        .removeClass("epidemicOfClose")
                        .text("该地址2公里内有：疫情-防控区，请注意疫情防控。");
                } else if (data === 2) {
                    $("#spanEpidemicControlTip").text('很抱歉，由于您提供的地址可能归属管控区，根据相关防疫规定，工程师暂时无法上门服务，给您带来的不便敬请谅解。');
                    $("#divEpidemicControlTip")
                        .addClass("epidemicOfClose")
                        .removeClass("epidemicOfOpen")
                        .text("该地址2公里内有：疫情-管控区，可联系客户是否继续服务。");
                } else if (data === 3) {
                    $("#spanEpidemicControlTip").text('很抱歉，由于您提供的地址可能归属封控区，根据相关防疫规定，工程师暂时无法上门服务，给您带来的不便敬请谅解。');
                    $("#divEpidemicControlTip")
                        .addClass("epidemicOfClose")
                        .removeClass("epidemicOfOpen")
                        .text("该地址2公里内有：疫情-封控区，可联系客户是否继续服务。");
                } else {
                    $("#spanEpidemicControlTip").text('');
                    $("#divEpidemicControlTip").text('');
                }
            },
            function (msg) {
                console.log(msg);
                $("#spanEpidemicControlTip").text('');
                $("#divEpidemicControlTip").text('');
            }
        );
    }

    /**
     *  清空疫情相关参数
     */
    function cleanEpidemicControl() {
        $("#spanEpidemicControlTip").text('');
        $("#divEpidemicControlTip").text('');
    }

    /**
     * 更多
     */
    function initMoreModal() {
        $('[data-toggle="allModal"]').on('click', function() {
            var that = $('[data-toggle="modal"]');
            console.log(that)
            if (that.hasClass('layui-icon-up')) {
                that.removeClass("layui-icon-up").addClass("layui-icon-down");
            } else {
                that.removeClass("layui-icon-down").addClass("layui-icon-up");
            }

            var targetId = that.data('target');
            if (!targetId) {
                return;
            }
            var $target = $(targetId);
            if ($target.hasClass("layui-hide")) {
                $target.removeClass("layui-hide").addClass("layui-show");
            } else {
                $target.removeClass("layui-show").addClass("layui-hide");
            }
        });
    }

    /**
     * 初始化下拉框
     */
    function initAllSelect() {
        initShopSelect();
    }

    function initShopSelect(){
        if (!existShopSelect()) {
            return;
        }
        let customSearch = (selectId, options) => {
            let newOptions = zmnOmsSelect.mergeOptions(selectId, options, {
                propMap: {  //选项参数映射配置
                    name: "showShopName",   //显示值
                    value: "internalShopId",  //选中值
                    internalShopId: "internalShopId",
                    internalShopName: "internalShopName",
                    internalBranchShopName: "internalBranchShopName",
                    externalShopId: "externalShopId",
                    cooperationId: "cooperationId"
                },
                isRadio: true,
                remote: {
                    body: false,
                    enable: true,
                    search: true,
                    url: GET_EXTERNAL_SHOP_URL,
                    events: {
                        params: function (searchValue, limitPermit) {
                            return {
                                keyword: searchValue
                            }
                        }
                    }
                }
            })
            return zmnOmsSelect.searchBox(selectId, newOptions);
        };

        var searchedValue;
        if (json.orderExternalShop && json.orderExternalShop.internalShopId) {
            searchedValue = json.orderExternalShop.internalShopId;
        }

        let searchBoxDemo = customSearch('externalShopInfo', {
            name: "externalShopInfoSelelct",
            searchedValue: searchedValue || null,
            selectedValues: searchedValue || [],
            events: {
                dataMap: function (resultData) {
                    console.log("==========接口返回数据=========");
                    let data = [];
                    if (resultData.status == 200) {
                        data = resultData.data;
                    }
                    return {
                        data: data
                    };
                },
                changed: function (values) {
                    // 下单渠道禁止修改
                    if ($('#channelId').prop('disabled')) {
                        return;
                    }
                    if (!values) {
                        return;
                    }
                    if (values.length < 1) {
                        return;
                    }
                    let externalShopInfo = zmnOmsSelect.getXmSelect('externalShopInfo').getValue()[0];
                    if (!externalShopInfo.cooperationId) {
                        return;
                    }
                    if (!json.channelList) {
                        return;
                    }
                    json.channelList.forEach(function (item, index) {
                        if (externalShopInfo.cooperationId === item.value) {
                            $('#channelId').val(item.value);
                            form.render("select");
                            var select = 'dd[lay-value=' + item.value + ']';
                            $('#channelId').siblings("div.layui-form-select").find('dl').find(select).click();
                            return;
                        }
                    });
                }
            }
        });

        // 回显值
        if (json.orderExternalShop) {
            zmnOmsSelect.getXmSelect('externalShopInfo').setValue([
                {
                    name: json.orderExternalShop.showShopName,   //显示值
                    value: json.orderExternalShop.internalShopId,  //选中值
                    internalShopId: json.orderExternalShop.internalShopId,
                    internalShopName: json.orderExternalShop.internalShopName,
                    internalBranchShopName: json.orderExternalShop.internalBranchShopName,
                    externalShopId: json.orderExternalShop.externalShopId,
                    cooperationId: json.orderExternalShop.cooperationId
                }
            ]);
        }
    }

    function initClipboardEvent() {
        // 初始化剪切板控制器
        clipboard.init();

        // 初始化剪切板控制器
        let $clipboard = new ClipboardJS('.productCategTip', {
            text: function (trigger) {
                let $productCateg = $('input[name="productCategId"]:checked');
                if ($productCateg.length > 0) {
                    return $productCateg.attr("title");
                } else {
                    return '';
                }
            }
        });

        $clipboard.on('success', function(e) {
            layer.tips('复制成功', e.trigger, {
                time: 500,
                tips: [3, '#5FB878']
            })
        });

        // 初始化剪切板控制器
        let $productClipboard = new ClipboardJS('.quoteProductTip', {
            text: function (trigger) {
                let $quoteProduct = $('input[name="quoteProduct"]:checked');
                if ($quoteProduct.length > 0) {
                    return $quoteProduct.attr("title");
                } else {
                    return '';
                }
            }
        });

        $productClipboard.on('success', function(e) {
            layer.tips('复制成功', e.trigger, {
                time: 500,
                tips: [3, '#5FB878']
            })
        });
    }

    /**
     * 初始化页面
     */
    function initPage(options) {
        // 初始化复制事件
        initClipboardEvent();

        initAllSelect();
        // 初始化区域信息
        initServiceArea(getters.getCityId(), function() {
            var countyId = $('#countyId').attr('value');
            $('#countyId').val(countyId);
            layui.form.render("select");
            updateAreaList(countyId);

            // 校验疫情
            checkEpidemicControl();
        });

        // 初始化下次联系时间选择框
        renderNextTimeDatePicker();

        // 初始化页面事件
        initEvent();

        if (!options || !options.withoutPhoneVerify) {
            // 触发验证会员电话
            $('input[name="telephone"]').trigger("change");
        }

        // 初始化表单验证规则
        initVerifyRules();

        // 复制页面校验渠道城市
        if (options.isCopy) {
            checkChannelIdAndCityId(getters.getChannelId(), getters.getCityId());
        }

        // 更多
        initMoreModal();
        dutyStatusCheck($("#duty-time-checkbox").is(':checked'));

        if (getters.getCityId()) {
            checkGrid(getters.getCityId(), function() {
                if (options.isCopy || getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
                    if (isGrid) {
                        // 初始化行政服务商
                        initGridCompany();
                    } else {
                        initCompanyInfo();
                    }
                }
                initDutyTime();
            });
        }
        // 校验取消重复
        checkDuplicateOrder();
        //下单渠道是否 选择外部店铺
        checkSelectExternalShop(getters.getChannelId());

        // 检验是否要去加载提前报价信息
        initCheckAdvanceQuote();
        // 加载价格表
        loadAdvanceQuotePriceTable();
    }

    // 校验电话
    $("#telephone, #telephone2, #telephone3").on("change", function() {
        checkDuplicateOrder();
    });

    /**
     *  校验取消重复
     */
    function checkDuplicateOrder(){
        let type = getters.getOrderType();
        if (type != ORDER_TYPE_ENUM.NEW) {
            return;
        }
        let telephone = getters.getTelephone();
        let telephone2 = getters.getTelephone2();
        let telephone3 = getters.getTelephone3();
        let productShowType = getters.getProductShowType();
        let productId = getters.getProductId();
        let orderId = getters.getOrderId();
        if (!productId || !telephone){
            return;
        }
        $http.$get(GET_DUPLICATE_ORDER_ID_URL,
            {
                plat:getters.getPlat(),
                bizType:getters.getBizType(),
                orderId: orderId,
                telephone: telephone,
                telephone2: telephone2,
                telephone3: telephone3,
                productShowType: productShowType,
                productId: productId
            }).then(function (data) {
            if (data) {
                $("#order-duplicate-tips").html("此用户有疑似相同的订单正在服务")
            } else {
                $("#order-duplicate-tips").html('');
            }
        }, function (msg) {
            $("#order-duplicate-tips").html('');
        })
    }


    exports("oms_order_add_common", {
        init: function(ops) {
            options = ops;

            if (options.isNew === true) {
                // 新增订单，使用渠道开通的城市
                CITY_URL = '/area/channel/city/list.action';
            }

            // 初始化页面
            initPage(ops);
        },
        initCompany: function(cityId) {
            cityId = cityId || getters.getCityId();
            initCompanyInfo(cityId);
        },
        getters: getters,
        goDetail: goWorkDetail,
        goModifyDetail: goWorkModifyDetail,
        resetCitySelect: function() {
            renderCitySelect(json.cityList);
        },
        isRework: function() {
            return getters.getOrderType() === '2';
        },
        calculateProductAmount: calculateProductAmount,
        renderNewOrderPost: renderNewOrderPost
    });
});